Prepare modular combination tables
Use factorial inverses only under their prime and range conditions.
Understand the idea
For prime p and 0 ≤ n ≤ N < p, compute C(n,r) using factorial[n] × inverseFactorial[r] × inverseFactorial[n−r] modulo p. Build factorials forward, invert the last factorial once, and fill inverse factorials backward.
Trace a small example
With p = 7, C(5,2) = 10 gives residue 3. The backward update invFact[i−1] = invFact[i] × i modulo p follows from i! = i × (i−1)!. Reuse tables only for their original modulus.
Conditions and cost
Preparation takes O(N + log p), O(N) storage, then O(1) per query. For N ≥ p, a factorial becomes zero modulo p and has no inverse. Small bounds with arbitrary positive moduli can instead use Pascal addition.
Why does the simple method fail when N ≥ p?
Turn the idea into code
Compute C(6,2) modulo 7 and check the assumptions.
Give me a hint
6 < 7 and 7 is prime.
Show the explained solution
C(6,2) = 15, giving residue 1; the table assumptions hold.
Your notes
Mark complete when you can explain it yourself.