Created
November 22, 2014 19:25
-
-
Save binhngoc17/a8c055c2cd01fd637c1e to your computer and use it in GitHub Desktop.
mod funcs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
long modPow(long a, long x, long p) { | |
//calculates a^x mod p in logarithmic time. | |
long res = 1; | |
while(x > 0) { | |
if( x % 2 != 0) { | |
res = (res * a) % p; | |
} | |
a = (a * a) % p; | |
x /= 2; | |
} | |
return res; | |
} | |
long modInverse(long a, long p) { | |
//calculates the modular multiplicative of a mod m. | |
//(assuming p is prime). | |
return modPow(a, p-2, p); | |
} | |
long modBinomial(long n, long k, long p) { | |
// calculates C(n,k) mod p (assuming p is prime). | |
long numerator = 1; // n * (n-1) * ... * (n-k+1) | |
for (int i=0; i<k; i++) { | |
numerator = (numerator * (n-i) ) % p; | |
} | |
long denominator = 1; // k! | |
for (int i=1; i<=k; i++) { | |
denominator = (denominator * i) % p; | |
} | |
// numerator / denominator mod p. | |
return ( numerator* modInverse(denominator,p) ) % p; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment