计算阶乘和排列组合数的小程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#!/usr/bin/perl 
 
use strict;
use warnings;
 
use Getopt::Std;
use Math::Counting;
 
my %opts;
my ( $n, $r );
 
getopts( 'aecfpn:r:h', %opts );
 
if ( @ARGV == 0 || exists $opts{h} ) {
    print STDOUT ;
    exit(0);
}
 
if ( exists $opts{n} ) {
    $n = $opts{n};
}
elsif ( @ARGV == 1 || @ARGV == 2 ) {
    $n = $ARGV[0];
}
else {
    print STDOUT ;
    exit(0);
}
 
if ( exists $opts{r} ) {
    $r = $opts{r};
}
elsif ( @ARGV == 2 ) {
    $r = $ARGV[1];
}
elsif ( defined($n) ) {
}
else {
    print STDOUT ;
    exit(0);
}
 
unless ( $n =~ /^d+$/ ) {
    print "Please input an NATURAL NUMBER for "n"!n";
    exit(0);
}
if ( defined($r) && $r !~ /^d+$/ ) {
    print "Please input an NATURAL NUMBER for "r"!n";
    exit(0);
}
 
my $f  = Math::Counting::bfact($n);
my $fe = Math::Counting::factorial($n);
my ( $p, $pe, $c, $ce );
if ( defined($r) ) {
    $p = Math::Counting::bperm( $n, $r );
    $pe = Math::Counting::permutation( $n, $r );
    $c = Math::Counting::bcomb( $n, $r );
    $ce = Math::Counting::combination( $n, $r );
}
 
if ( exists $opts{e} ) {
    $f = $fe;
    $p = $pe;
    $c = $ce;
}
 
if ( exists $opts{a}
    || ( !( exists $opts{f} ) && !( exists $opts{p} ) && !( exists $opts{c} ) )
  )
{
    if ( defined($r) ) {
        print "$n!     = $fn";
        print "P($n,$r) = $pn";
        print "C($n,$r) = $cn";
    }
    else {
        print "$n!     = $fn";
    }
}
 
if ( exists $opts{f} ) {
    print "$fn";
}
 
if ( exists $opts{p} ) {
    if ( defined($r) ) {
        print "$pn";
    }
    else {
        print
          "Please input the "r" if you want to compute the permutations.n";
    }
}
 
if ( exists $opts{c} ) {
    if ( defined($r) ) {
        print "$cn";
    }
    else {
        print
          "Please input the "r" if you want to compute the combinations.n";
    }
}
 
__DATA__
 
Program:   fpc.pl (v20110927)
Author:    Yixf (yixf1986@gmail.com)
Summary:   Compute the factorial, number of permutations/arrangements and number of combinations.
 
Usage:   fpc.pl [OPTIONS] (N|-n N) (R|-r R)
 
Options:
	-a  (All) Compute the factorial, permutations/arrangements and combinations. [default]
	-e  Use the scientific notation.
	-f  (Factorial) Return the number of arrangements of n.
	-p  (Permutation) Return the number of arrangements of r elements drawn from a set of n elements.
	-c  (Combination) Return the number of ways to choose r elements from a set of n elements.
	-n  (N) The number of elements to draw from.
	-r  (R) The number of elements to choose.