-
Notifications
You must be signed in to change notification settings - Fork 4
/
exec6-10.cpp
45 lines (39 loc) · 1.05 KB
/
exec6-10.cpp
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
#include <iostream>
using namespace std;
double production(int a, int b);
double permutation(int n, int m);
double combination(int n, int m);
// calculate permutations or combinations
int main() {
cout << "Please enter two integers n, m (0 <= m <= n)"
" and an operator ('p' for permutation, 'c' for combination)\n";
int n, m;
char op;
while (cin >> n >> m >> op) {
if (m < 0 || m > n) {
cerr << "m must be between 0 and n" << endl;
continue;
}
if (op != 'p' && op != 'c') {
cerr << "operator must be 'p' or 'c'" << endl;
continue;
}
cout << (op == 'p' ? permutation(n, m) : combination(n, m)) << endl;
}
return 0;
}
// return a * (a+1) * ... * b
double production(int a, int b) {
double p = 1;
while (a <= b)
p *= a++;
return p;
}
// return P(n, m)
double permutation(int n, int m) {
return production(n - m + 1, n);
}
// return C(n, m)
double combination(int n, int m) {
return permutation(n, m) / production(1, m);
}