-
Notifications
You must be signed in to change notification settings - Fork 3
/
ncr.cpp
81 lines (72 loc) · 2.31 KB
/
ncr.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
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
>> ncr % m
>>> Resources:
T-1 : https://cp-algorithms.com/combinatorics/binomial-coefficients.html
T-2 : https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/
>>> Implementation
ll fact[N], facti[N];
ll be(ll a,ll b)
{
if(b==0)
{
return 1;
}
if(b==1)
{
ll ans=a%M;
return ans;
}
if(b%2==0)
{
a=a%M;
a=(a*a)%M;
ll ans=be(a,b/2)%M;
return ans;
}
else
{
a=a%M;
ll val=a;
a=(a*a)%M;
ll ans=be(a,b/2)%M;
ans=(val*ans)%M;
return ans;
}
}
ll factinv(ll val)
{
/* Modulo Property (a)^-1 = ((a)^(m-2))% m */
/* Only If m is a prime */
return be(val, M-2);
}
void factorialinv()
{
facti[N-1]=factinv(fact[N-1]);
for(ll i=N-2;i>=0;i--)
{
facti[i]=facti[i+1]*(i+1);
facti[i]%=M;
}
}
void factorial()
{
fact[0]=fact[1]=1;
for(ll i=2;i<N;i++)
{
fact[i]=fact[i-1]*i;
fact[i]%=M;
}
factorialinv();
}
ll pnc(ll x,ll y)
{
if(y>x)
{
return 0;
}
ll num=fact[x];
num*=facti[x-y];
num%=M;
num*=facti[y];
num%=M;
return num;
}