I'm trying to compute nCr modulo p, where p is a prime.
One approach I've tried is to compute n! / (r! * (n-r)!) modulo p using multiplicative inverses, but this fails when either r or n - r is greater than or equal to p, since then the factorials are zero modulo p and the inverses don't exist.
What method works in all cases and not just when multiplicative inverses exist?
I'd use Lucas's theorem
C(14,1), p=13
N = 14 = 1 * 13 + 1
K = 1 = 0 * 13 + 1
C(N,K) mod p = (C(1,0) mod 13 ) * (C(1,1) mod 13) = 1
Calculating nCr modulo p,p is prime number
Another Method: You can also use pascal method to calculate nCr
As, for any nCr,you can use
row[0]=1;
for(i=1;i<n/2;i++)
{
row[i]=row[i-1]*(n-i+1)/i
}
for(i=n/2;i<=n;i++)
{
row[i]=row[n-i]
}
In this you have to take modulo_inverse of (i) using any of the above way( Fermat's little theorem or Extended Euclidean algorithm )
Reference: Best known algos for calculating nCr % M
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With