Skip to content

Instantly share code, notes, and snippets.

@Jangwa
Last active July 12, 2020 13:31
Show Gist options
  • Save Jangwa/8671151 to your computer and use it in GitHub Desktop.
Save Jangwa/8671151 to your computer and use it in GitHub Desktop.
For larger factorials you can either write big factorial library or use a language like Python. The time complexity is O(n). If we have to calcuate nCr mod p(where p is a prime), we can calculate factorial mod p and then use modular inverse to find nCr mod p. If we have to find nCr mod m(where m is not prime), we can factorize m into primes and …
#include<iostream>
using namespace std;
#include<vector>
/* 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 C(int n, int r, int MOD)
{
vector<long long> f(n + 1,1);
for (int i=2; i<=n;i++)
f[i]= (f[i-1]*i) % MOD;
return (f[n]*((InverseEuler(f[r], MOD) * InverseEuler(f[n-r], MOD)) % MOD)) % MOD;
}
int main()
{
int n,r,p;
while (~scanf("%d%d%d",&n,&r,&p))
{
printf("%lld\n",C(n,r,p));
}
}
@dgr8singh
Copy link

if MOD=10^9+6, MOD have prime factors 2 and 5*(10^8)+3 ,can you tell how to find nCr %MOD (means how to apply Chinese Remainder Theorem) ? . Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment