-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNCR_mod_M.cpp
More file actions
86 lines (76 loc) · 1.74 KB
/
Copy pathNCR_mod_M.cpp
File metadata and controls
86 lines (76 loc) · 1.74 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
/**
(588 choose 277) % 5 = ?
Representation of 588 in base of 5 = 4323
Representation of 277 in base of 5 = 2102
Now your answer reduces to = ((4 choose 2)(3 choose 1)(2 choose 0)(3 choose 2)) % 5
= (6 * 3 * 1 * 3) % 5
= 54 % 5
= 4**
**/
#include<iostream>
using namespace std;
#include<vector>
/* This function calculates power of p in n! */
int countFact(int n, int p)
{
int k=0;
while (n>=p)
{
k+=n/p;
n/=p;
}
return k;
}
/* This function calculates (a^b)%MOD */
long long pow(int a, int b, int MOD)
{
long long x=1,y=a;
while(b > 0)
{
if(b%2 == 1)
{
x=(x*y);
if(x>MOD) x%=MOD;
}
y = (y*y);
if(y>MOD) y%=MOD;
b /= 2;
}
return x;
}
/* Modular Multiplicative Inverse
Using Euler's Theorem
a^(phi(m)) = 1 (mod m)
a^(-1) = a^(m-2) (mod m) */
long long InverseEuler(int n, int MOD)
{
return pow(n,MOD-2,MOD);
}
long long factMOD(int n, int MOD)
{
long long res = 1;
while (n > 0)
{
for (int i=2, m=n%MOD; i<=m; i++)
res = (res * i) % MOD;
if ((n/=MOD)%2 > 0)
res = MOD - res;
}
return res;
}
long long C(int n, int r, int MOD)
{
if (countFact(n, MOD) > countFact(r, MOD) + countFact(n-r, MOD))
return 0;
return (factMOD(n, MOD) *
((InverseEuler(factMOD(r, MOD), MOD) *
InverseEuler(factMOD(n-r, MOD), MOD)) % MOD)) % MOD;
}
int main()
{
int n,r,p;
while (~scanf("%d%d%d",&n,&r,&p))
{
printf("%lld\n",C(n,r,p));
}
}