Math Fundamentals18 sections · 814 units
Open in Course

Combinations Modulo M

(For competitive programming)

In programming contests, you often compute C(n,k) mod M. Direct computation fails for large n due to overflow.

Use modular multiplicative inverse: C(n,k) mod M = (n! mod M) × (inverse of k! mod M) × (inverse of (n-k)! mod M). Fermat's little theorem finds inverses when M is prime.

Precompute factorials and their inverses up to n. Then answer queries in O(1) time. This is the standard approach for competitive programming.