Hello folks, problem that i am gonna discuss is one of the standard problem that we very usually see in contest and it is as follow. You are given certain combinatoric problem which finally ends up with answer n Cr (n choose r),adding to the constraints since value of n Cr can be very large then you are asked to take modulus of the answer.
Solution to above problem : there are two case, first case when MOD is prime and case two when MOD is not prime, in this post i will be sharing answer to when MOD is prime. To solve above problem we use Lucas Theorem which states as follow.
LUCAS THEOREM
If MOD is a prime number, and N has base MOD representation (aj,...,a1,a0) and r has base MOD representation (bj,...,b1,b0), then (N CHOOSE R) is congruent [mod MOD] to
(N choose R) modulus MOD = ((aj CHOOSE bj)...(a1 CHOOSE b1) (a0 CHOOSE b0)) modulus MOD
Let me make it more clear with example, for instance you have answer as (588 choose 277) % 5, then
**(588 choose 277) % 5 = ?
Representation of 588 in base of 5 = 4323
Representation of 277 in base of 5 = 2102
Now your answer reduces to = ((4 choose 2)(3 choose 1)(2 choose 0)(3 choose 2)) % 5
= (6 * 3 * 1 * 3) % 5
= 54 % 5
= 4**
Important tip to calculate (aj choose bj) you can pre compute factorial upto MOD-1 and store that in array and hence you can compute (aj choose bj) in O(1) time.
Important observation : their might be certain cases when (aj < bj) in that case simply return 0 as your answer, why ? left for you geek :P
One of the limitation of this theorem is, it works fine when the value of MOD is small if value of MOD is itself large then it become difficult to store factorial of values up to MOD-1.