-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombinatorics.cpp
More file actions
86 lines (67 loc) · 1.2 KB
/
Combinatorics.cpp
File metadata and controls
86 lines (67 loc) · 1.2 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
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
const int mod = 1e9 + 7;
const int kN = 1e5;
int f[1 + kN], invf[1 + kN];
/* int64_t nck(int N, int K) { // N choose K in linear time
if (K < N - K) {
K = N - K;
}
int64_t ans = 1;
int p = 2;
for (int i = K + 1; i <= N; ++i) {
ans *= i;
while (p <= N - K && ans % p == 0) {
ans /= p++;
}
}
return ans;
} */
void addSelf(int &x, const int &y) {
x += y;
if (x >= mod) {
x -= mod;
}
}
int add(int x, const int &y) {
addSelf(x, y);
return x;
}
void multSelf(int &x, const int &y) {
x = (int64_t)x * y % mod;
}
int mult(int x, const int &y) {
multSelf(x, y);
return x;
}
int Pow(int x, int n) {
int ans = 1;
while (n) {
if (n & 1) {
multSelf(ans, x);
}
multSelf(x, x);
n >>= 1;
}
return ans;
}
int invers(int x) {
return Pow(x, mod - 2);
}
int nck(int n, int k) {
if (n < k) {
return 0;
}
if (n == k) {
return 1;
}
return mult(f[n], mult(invf[k], invf[n - k]));
}
void computeFactorials(int n) {
f[0] = 1;
for (int i = 1; i <= n; ++i) {
f[i] = mult(f[i - 1], i);
}
invf[n] = invers(f[n]);
for (int i = n - 1; i >= 0; --i) {
invf[i] = mult(invf[i + 1], i + 1);
}
}