Fast n choose k mod p for large n?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Computing n choose k mod p efficiently depends on what is large and what is fixed. If n is huge but p is a prime and relatively small, Lucas's theorem is often the key tool. If n is only moderately large and you need many queries under the same prime modulus, factorial precomputation with modular inverses is usually the fastest practical approach.
The Basic Formula Is Not Enough
The direct combinatorial formula is:
C(n, k) = n! / (k! (n-k)!)
But under modular arithmetic you cannot divide directly. For prime p, the usual trick is to replace division with multiplication by modular inverses.
That gives:
C(n, k) mod p = fact[n] * inv_fact[k] * inv_fact[n-k] mod p
where the inverse values are computed modulo p.
Fast Method for Moderate n
When n is not astronomically large and p is prime, precompute factorials and inverse factorials:
This gives O(1) query time after O(n) preprocessing.
Lucas's Theorem for Huge n
If n is very large relative to p, Lucas's theorem helps by decomposing the problem into base-p digits:
C(n, k) mod p = product of C(n_i, k_i) mod p
where n_i and k_i are the digits of n and k in base p.
That means the giant problem becomes a product of much smaller binomial problems.
Example implementation:
This is the standard fast answer when p is prime and n is too large for full factorial precomputation up to n.
Use Symmetry Too
Always reduce k with:
k = min(k, n-k)
That small step can significantly reduce work in algorithms that iterate over k or depend on the smaller side of the binomial coefficient.
Even when using Lucas's theorem, this symmetry can still simplify the subproblems you solve.
Common Pitfalls
- Trying to divide directly under modulo arithmetic instead of using modular inverses.
- Forgetting that the common inverse trick depends on
pbeing prime. - Precomputing factorials up to a gigantic
nwhen Lucas's theorem is the right tool. - Ignoring the
k > ncase, which should return0. - Using a method for prime moduli on a composite modulus without rethinking the number theory.
Summary
- For prime
pand moderaten, factorial plus inverse-factorial precomputation is the standard fast method. - For huge
n, Lucas's theorem is the usual answer. - Modular inverses replace division in the binomial formula.
- Reducing
ktomin(k, n-k)is a simple but useful optimization. - The right algorithm depends on the size of
n, the size ofp, and whetherpis prime.

