C++ – How to we compute N choose K modulus a prime number without overflow

algorithmcmathmodulo

How can we computer (N choose K)% M in C or C++ without invoking overflow ?

For the particular case when N (4<=N<=1000) and K (1<=K<=N) and M = 1000003.

Best Answer

To compute (n choose k) % M, you can separately compute the nominator (n!) modulus M and the denominator (k!*(n - k)!) modulus M and then multiply the nominator by the denominator's modular multiplicative inverse (in M). Since M is prime, you can use Fermat's Little Theorem to calculate the multiplicative inverse.

There is a nice explanation, with sample code, on the following link (problem SuperSum):

http://www.topcoder.com/wiki/display/tc/SRM+467