Implement a class Binomial(max_n, p=MOD) where MOD = 1_000_000_007 (define it in your solution). p is a prime larger than max_n.
- The constructor precomputes whatever it needs.
.ncr(n, r)returnsC(n, r) mod pfor0 <= n <= max_n. Return0whenr < 0orr > n.
b = Binomial(10)
b.ncr(5, 2) # 10
b.ncr(10, 0) # 1
b.ncr(4, 5) # 0
b.ncr(4, -1) # 0
Binomial(10, 13).ncr(10, 5) # 5 (252 mod 13)
Constraints: 0 <= max_n <= 10^6.
⭐ Bonus: a speed test that builds a table for max_n = 10^6 and asks 200,000 queries earns a star for an O(max_n) build (plus one O(log p) inverse) and O(1) ncr. A fresh modular inverse per index or per query is too slow for that.
Show hint
C(n, r) = n! / (r! (n-r)!), so tables of factorials and of their inverses mod p answer each query with two multiplications. You only need one modular inverse (via Fermat's little theorem): the rest of the inverse table follows by walking down, since 1/(i-1)! = i / i!.