Learn
Binomial Coefficient (nCr mod p)
The binomial coefficient , also written as or "n choose r", counts the number of ways to choose items from items. The formula requires modular inverse for modular arithmetic.
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
The binomial coefficient , also written as or "n choose r", counts the number of ways to choose items from items. The formula requires modular inverse for modular arithmetic.
Apply what you learned by solving the practice problem for Combinations (nCr mod p).
Go to Practice ProblemYou precompute factorials and inverse factorials, then compute .
function precompute(maxN, mod):
fact = array of size maxN + 1
invFact = array of size maxN + 1
fact[0] = 1
for i from 1 to maxN:
fact[i] = (fact[i-1] * i) mod mod
invFact[maxN] = modInverse(fact[maxN], mod)
for i from maxN - 1 down to 0:
invFact[i] = (invFact[i+1] * (i+1)) mod mod
return (fact, invFact)
function nCr(n, r, fact, invFact, mod):
if r < 0 or r > n:
return 0
return (fact[n] * invFact[r] mod mod) * invFact[n-r] mod mod
Inverse factorial optimization: You compute once, then derive smaller inverse factorials: .
Multiple queries: Precomputation gives you per query after setup.
Applications: You use binomial coefficients for probability calculations, Pascal's triangle, counting paths in grids, and combinatorial problems.
Time complexity: precomputation, per query.
Space complexity: for factorial and inverse factorial arrays.