I have often encountered calculating nCr problems the last one being one of the IIIT-M problems but it probably had weak test cases that got easy solutions AC. The other one https://cs3.interviewstreet.com/challenges/dashboard/#problem/50877a587c389 of codesprint was completey out of my minds and hands , I tried the inverse euler , power of p in n! ( I would also like if someone could explain me the theory of this method ) but all went in vain . Anyone who could suggest probably the best algos for cases when nCr is to be calculated with large n and r with and without % M where M is prime/not prime + the above method which I coded but couldnâ€™t understand how it was so.

I encountered ^{n}C_{r} for the first time on GCJ 08, Round 3 Problem D â€¦ link to analysis.

The first key idea is that of Lucasâ€™ Theorem.

Lucasâ€™s Theorem reduces ^{n}C_{r} % M to

(^{n0}C_{r0} % M) (^{n1}C_{r1} % M) â€¦ (^{nk}C_{rk} % M)

Where,

(n_{k}n_{k-1}â€¦n_{0}) is the base M representation of n

(r_{k}r_{k-1}â€¦r_{0}) is the base M representation of r

- Note, if any of the above terms is zero because r
_{i}> n_{i}or any other degeneracy, then the binomial coefficient^{n}C_{r}% M = 0

This means that any of the terms in the expansion of ^{ni}C_{ri} is not divisible by M. But this is only half the job done.

Now you have to calculate ^{n}C_{r} % M (ignoring subscripts for brevity) for some 0 â‰¤ r â‰¤ n < M

There are no ways around it, but to calculate

[ n! / ( r! (n-r)! ) ] % M

Without loss of generality, we can assume r â‰¤ n-r

Remember, you can always do the Obvious. Calculate the binomial and then take a modulo. This is mostly not possible because the binomial will be too large to fit into either int or long long int (and Big Int will be too slow)

This can then be simplified by using some clever ideas from Modular Arithmetic.

- If A*B % M = 1, A and B are modular multiplicative inverses of each other.

For brevity, we say B % M = A^{-1} % M

It is not always possible to calculate modular multiplicative inverses. If A and M are not co-prime, finding a B will not be possible.

For example, A = 2, M = 4. You can never find a number B such that 2*B % 4 = 1

Most problems give us a prime M. This means calculating B is always possible for any A < M.

For other problems, look at the decomposition of M. In the codesprint problem you mentioned

142857 = 3^{3} * 11 * 13 * 37

You can find the result of ^{n}C_{r} % m for each m = 27, 11, 13, 37. Once you have the answers, you can reconstruct the answer modulo 142857 using Chinese Remainder Theorem. These answers can be found by Naive Methods since, m is small.

I have also seen problems where M is a product of large primes, but square free. In these cases, you can calculate the answers modulo the primes that M is composed of using modular inverses (a little more about that below), and reconstruct the answer using CRT.

I am yet to see a problem where M is neither, but if it is. I do not know if there is a way to calculate binomial coefficients generally (since you cannot calculate modular inverses, and neither can you brote force). I can dream of a problem where there are powers of small primes, but square-free larger ones for a Number Theory extravaganza.

There is one other way to calculate ^{n}C_{r} for any M which is small enough (say M â‰¤ 5000) or small n and r (say r â‰¤ n â‰¤ 5000) by using the following recursion with memoization

^{n}C_{r} = ^{n-1}C_{r} + ^{n-1}C_{r-1}

Since there are no divisions involved (no multiplications too) the answer is easy and precise to calculate even if the actual binomials would be very large.

So, back to calculating

[ n! / ( r! (n-r)! ) ] % M, you can convert it to

n * (n-1) â€¦ * (n-r+1) * r^{-1} * (r-1)^{-1} â€¦ * 1

Of course, each product is maintained modulo M.

This may be fast enough for problems where M is large and r is small.

But sometimes, n and r can be very large. Fortunately, such problems always have a small enough M

The trick is, you pre-calculate factorials, modulo M and pre-calculate inverse factorials, modulo M.

fact[n] = n * fact[n-1] % M

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

Modular Multiplicative Inverse for a prime M is in fact very simple. From Fermatâ€™s Little Theorem

A^{M-1} % M = 1

Hence, A * A^{M-2} % M = 1

Or in other words,

A^{-1} % M = A^{M-2} % M, which is easy (and fast) to find using repeated squaring.

There is one last link I wish to paste to make this complete. Modular inverses can also be found using the Extended Euclidâ€™s Algorithm. I have only had to use it once or twice among all the problems I ever solved.

I agree completely with what @kavishrox wroteâ€¦

Admins, would it be possible to have some sort of â€śpinâ€ť feature, so that the â€śtutorialâ€ť like posts wouldnâ€™t go down?

It would greatly help newbies and ofc make this community even more respected

Bruno

Would someone pls xplain me what are these â€śinverse factorialsâ€ť ??

To take as example :

â€ś142857 = 27 * 11 * 13 * 37. You can find the result of nCr % m for each m = 27, 11, 13, 37.â€ť

as 27 is not a prime, i hope we would have to resort to last method of finding all fact[n] and inverse-fact[n] for 27.

So we want nCr and we have x! for all x, WHY do we need inverse factorial ? Is it for (n-r)! and r!. To find inverse of (n-r) and r mod M and then multiply all of their factorials and then find % M.

How would you calculate nCr mod 27?

You canâ€™t use the inverse modulo here.

and also one canâ€™t do this by nCr=(n-1)Cr+(n-1)C(r-1)

given that the minimum space would be just 2 rows but

each of size r which in this case is 1000000000?

what if do not want modulo, just ncr which doesâ€™t fit in even long long?

What is the fastest among all the ways to calculate the value of nCr mod M? where M is definitely prime?

I think we should go for Inverse Modulo in this way. This is cheap, I mean **O(m)**.

r[i] = 1

for ( i = 2 ; i < limit ; i ++ )

r[i] = ( mod - (mod/i)*r[mod%i]%mod )%mod;

Here is the link Modulo_inverse

@imujjwalanand the last method described. Keep factorials and inverse-factorials modulo p. And you can get nCr % p in O(1) time with pre-computation of OÂ§ and space OÂ§

somebody plz upvote me .i need to ask some questions.

In Java this works quite ok for large N,K

private static BigInteger binomial(final int N, final int K) {

```
BigInteger ret = BigInteger.ONE;
for (int k = 0; k < K; k++) {
ret = ret.multiply(BigInteger.valueOf(N-k))
.divide(BigInteger.valueOf(k+1));
}
return ret;
```

}

Thank you for such a helpful answer, I have a conceptual doubt that why M needs to be prime for this for Modular

multiplicative inverse to be applied, I mean the condition is only that A and M should be coprime for the existence of inverse so M need not be prime for that.

Am I missing something , Can you please explain reason for M to be prime.

In c++ if you want to calculate nCr for large number of n and r, Here is the simplest logic to do that

```
void noOfCombination(int n, int k){
int i=0;
long long res=1;
if (k less_than n/2)
k = n - k;
for(i = 0; i less_than k; i++){
res *= (n-i);
res /= (i+1);
}
//output result
return;
}
```

enter code here

Once i had to find C(n,r) mod p for very large n,r,p but p was prime. To be exact n<=(2e9) ,r<=(1e9) and p=(2e9)+33

I really googled it but got no answer. So finally came up with an idea and it worked so i thought to share it .please correct me if it might fail in any case:-

The basic idea was to divide n into parts such that we can find any factorial in O(N) time where N can be adjusted according to questionâ€™s complexity, i took N to be 1e5 because i had to calculate only 3 factorial per testcase. So i divided it into 20000 (itâ€™s not random) groups each having product of all numbers in that group modulo p. 1st group contains number from 1 to 1e5 and 2nd group contains number from 1 to (2e5) and so on .generally ith group contains number from 1 to i*(1e5) letâ€™s say we are keeping these values in array f[20001].

please keep f[0] equal to 1 and keep the value of groups starting from 1 index.

**Please donâ€™t calculate your f array with in your program because that would be just stupid. I calculated with my IDE and kept it in a file and then copy ,pest **

Note:- if we increase the size of array f we can decrease the time to find factorial.

How to find factorial:-

letâ€™s say we have to find factorial of any random number 1567394027

steps:-

```
n=1567394027
k=1e5 //(group size)
a=n/k=15673
fac=f[a];
start=(a*k)+1 //1567300001;
for(int i=start;i<=n;i++)
fac=(fac*i)%p;
return fac;
```

total number of loops=(n%k)

as p is prime we can find multiplicative inverse in log(n) so i think this should work.

Please comment if you find anything wrong.

@gamabunta: this one is a godd recipe for a tutorial on codechef and topcoder @admins do try to make it a tutorial â€¦

@gamabunta: Firstly Thanks - Well written .

Lucasâ€™s Theorem reduces nCr % M to

(n0Cr0 % M) (n1Cr1 % M) â€¦ (nkCrk % M)

Where,

(nknk-1â€¦n0) is the base M representation of n

(rkrk-1â€¦r0) is the base M representation of r

This is only where M is prime â€¦ But in that particular problem M is not prime and so can we reduce it into Base form (And still Lucas Theorem Holds) ? And if we use CRT how can we use it ?

Thanks

Anu

@gamabunta: yes probably if you explain chinese remainder that would be even more beneficialâ€¦I have read it a lot many times but forget it too easily.