-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.cc
More file actions
62 lines (56 loc) · 1.54 KB
/
mod.cc
File metadata and controls
62 lines (56 loc) · 1.54 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
#define MOD 1000000007
inline int add(int a, int b, int mod=MOD) { return a + b < mod ? a + b : a + b - mod; }
inline void addBy(int &a, int b, int mod=MOD) { a = add(a, b, mod); }
inline int sub(int a, int b, int mod=MOD) { return a - b < 0 ? a - b + mod : a - b; }
inline void subBy(int &a, int b, int mod=MOD) { a = sub(a, b, mod); }
inline int mul(int a, int b, int mod=MOD) { return (LL)a * b % mod; }
inline void mulBy(int &a, int b, int mod=MOD) { a = mul(a, b, mod); }
/* a*x ≡ 1 (mod m) */
int inverse(int a, int mod = MOD)
{
int d = mod, x = 0, s = 1, q, r, t;
while (a != 0)
{
q = d / a, r = d % a;
d = a, a = r;
t = x - q * s, x = s, s = t;
}
if (d != 1) return -1;
return (x + mod) % mod;
}
inline int divide(int a, int b, int mod=MOD) { return mul(a, inverse(b, mod), mod); }
LL mul(LL a,LL b,LL mod=MOD){
LL x = 0,y=a%mod;
while(b > 0){
if(b%2 == 1){
x = x+y;
if(x >= mod) x -= mod;
}
y = y*2;
if(y >= mod) y -= mod;
b /= 2;
}
return x%mod;
}
template<class T>
T pow(T a, T b, T c=MOD){
T x=1,y=a; // ll is taken to avoid overflow of intermediate results
while(b > 0){
if(b%2 == 1){
x=mul(x, y, c);
}
y = mul(y, y, c); // squaring the base
b /= 2;
}
return x%c;
}
vector<int> factorial(1, 1);
int fact(int n) {
while(factorial.size() <= n)
factorial.push_back(mul(factorial.back(), factorial.size()));
return factorial[n];
}
int choose(int n, int k) {
if(n < k) return 0;
return divide(fact(n), mul(fact(k), fact(n-k)));
}