Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Edge case: nCr mod p is computed with factorials and Fermat inverses. Here n ≥ p.

Edge case: nCr mod p is computed with factorials and Fermat inverses. Here n ≥ p.
p = 7
fact = [1] * 11
for i in range(1, 11): fact[i] = fact[i-1] * i % p
inv = lambda x: pow(x, p - 2, p)
print(fact[10] * inv(fact[3]) * inv(fact[7]) % p)
What is printed?
  1. A. 1
  2. B. 6
  3. C. 0
  4. D. 3

Correct answer: C. 0

C(10, 3) = 120 ≡ 1 (mod 7), but 7! and 10! are both ≡ 0 mod 7, and pow(0, 5, 7) = 0, so the formula prints 0. Factorial-inverse nCr needs n < p; for n ≥ p use Lucas' theorem: C(10,3) ≡ C(1,0)·C(3,3) = 1.

More Coding Interview Problems questions

Exams that ask this topic