-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnCr_simple.cpp
More file actions
51 lines (39 loc) · 1.09 KB
/
nCr_simple.cpp
File metadata and controls
51 lines (39 loc) · 1.09 KB
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
/*
-> calculating nCr without computing factorials beforehand
-> current implementation for N <= 100
*/
int pw(int base, int exp) {
int res = 1;
//base %= M;
for (; exp; exp /= 2) {
if (exp % 2)
res = (res * base); // % M;
base = (base * base); // % M;
}
return res;
}
// primes[] can be changed according to requirements
vector<int> primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
// res[i] -> power of primes[i] in n!
vector<int> factPowers(int n) {
vector<int> res;
for (auto &c : primes) {
int tmp = n;
int cnt = 0;
while (tmp) {
tmp /= c;
cnt += tmp;
}
res.pb(cnt);
}
return res;
}
int nCr(int n, int r) {
vector<int> tot = factPowers(n);
vector<int> a = factPowers(r), b = factPowers(n - r);
int sz = (int)tot.size(), ans = 1;
for (int i = 0; i < sz; ++i) {
ans *= pw(primes[i], (tot[i] - (a[i] + b[i])));
}
return ans;
}