Calculating nCr mod M using inverse multiplicative factors

1.2k Views Asked by At

The method used for calculating nCr mod M is:

fact[n] = n * fact[n-1] % M ifact[n] = modular_inverse(n) * ifact[n-1] % M

And then nCr is calculated as fact[n]*ifact[r]*ifact[n-r] But in the example 5C4 mod 3, we get fact[1]=1, fact[2]=2, fact[3]=0,fact[4]=0,fact[5]=0, so the overall ans is 0 according to this method, whereas the ans should be 5%3 = 2. Whats the mistake with this method?

1

There are 1 best solutions below

0
On

That is not the way to calculate $\binom{n}{r} \pmod m$.
First the modular inverse, you must have $(r!,m)=1,((n-r)!,m)=1$..not the way with $m$ being so little. You can do it without any problem with $m>r!$. The mistake is that you are also dividing by some "0" and they cancel out. If you want to keep that method i suggest you to use Legendre decomposition of the factorial and keep the primes canceled out and some modular exponentiation will help out.
Example $5!=2^3*3*5,4!=2^3*3,1!=1$ So, $\frac{5!}{4!}=5$.

The way to do it is by applying the pascal recursion i.e., $\binom{n}{r}=\binom{n-1}{r}+\binom{n-1}{r-1}$ because, you do not need to do any division of any kind.

If $m$ is prime, another cool way is by applying the Lucas theorem.

Hope it helps.