Learn / Maths for DSA

nCr

C(n, r) modulo a prime is fastest with precomputed factorials and inverse factorials: C(n, r) = n! × (r!)⁻¹ × ((n - r)!)⁻¹. For small n, Pascal's rule C(n, r) = C(n-1, r-1) + C(n-1, r) needs no inverses. The sheets this guide follows have no problems for this pattern beyond those in DP.

How to recognise it

  • Counting ways to choose items, paths on a grid, or arrangements with repeats.
  • Many nCr queries with the same modulus.
  • n up to about 10⁶.

Precomputation

fact[0] = 1; fact[i] = fact[i - 1] × i
invfact[N] = power(fact[N], M - 2); invfact[i - 1] = invfact[i] × i
C(n, r) = 0 if r < 0 or r > n else fact[n] × invfact[r] × invfact[n - r]

See the binomial coefficient problem in the DP recipe lesson for the Pascal's triangle version.

Common mistakes

  • Missing the r > n check.
  • Overflow in the products.

Problems

No problems listed for this pattern yet.

Check yourself

How many queries can precomputed factorials answer?

How are inverse factorials filled quickly?

Grid paths from the top-left to the bottom-right of an m × n grid moving right and down?