-
Notifications
You must be signed in to change notification settings - Fork 16
/
combination_count.cpp
69 lines (58 loc) · 1.48 KB
/
combination_count.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
#include <iostream>
using namespace std;
int MOD = 1e9+7;
int fact(int n)
{
long long res = 1;
for (int i = 2; i <= n; i++)
res = (res * i) % MOD;
return res;
};
int power(int x, unsigned int y){
if (y == 0)
return 1;
long long p = power(x, y/2) % MOD;
p = (p * p) % MOD;
return (y%2 == 0)? p : (x * p) % MOD;
};
// Function to return gcd of a and b
int gcd(int a, int b){
if (a == 0)
return b;
return gcd(b%a, a);
};
// Function to find modular inverse of a under modulo m
// Assumption: m is prime
int modInverse(int a){
int g = gcd(a, MOD);
if (g != 1){
//Fermat's little theorem only works only when m is prime!
return -1;
}else{
// If a and m are relatively prime, then modulo inverse
// is a^(m-2) mod m
/*
From Fermat's little theorem,
when a is not divisible by p,
a^(p-1) mod m = 1
here we choose p as m,
so a^(m-1) mod m = 1
this is equal to saying that
a * a^(m-2) mod m = 1
so we can say that a^(m-2) mod m is the inverse of a
*/
return power(a, MOD-2);
}
};
int nCr(int n, int r)
{
long long fr_inverse = modInverse(fact(r));
long long fnr_inverse = modInverse(fact(n - r));
return ((fact(n) * fr_inverse) % MOD * fnr_inverse) % MOD;
};
int main()
{
cout << nCr(10, 5) << endl; //252
cout << nCr(70, 30) << endl; //709329438
return 0;
}