Data Structures & AlgorithmsVery hardProduct company OA

Problem: Compute C(n, r) mod a SMALL prime p = 7 when n ≥ p: Lucas' theorem versus factorials with Fermat inverses.

Problem: Compute C(n, r) mod a SMALL prime p = 7 when n ≥ p: Lucas' theorem versus factorials with Fermat inverses.
p = 7
fact = [1] * p
for i in range(1, p): fact[i] = fact[i - 1] * i % p
def small(n, r):
    if r < 0 or r > n: return 0
    return fact[n] * pow(fact[r], p - 2, p) * pow(fact[n - r], p - 2, p) % p
def lucas(n, r):
    res = 1
    while n or r:
        res = res * small(n % p, r % p) % p
        n //= p; r //= p
    return res
from math import comb
F = [1] * 1001
for i in range(1, 1001): F[i] = F[i - 1] * i % p
naive = F[1000] * pow(F[3] * F[997] % p, p - 2, p) % p
print(lucas(1000, 3), comb(1000, 3) % p, naive)
What is printed?
  1. A. 6 6 6
  2. B. 0 6 0
  3. C. 6 6 0
  4. D. 6 0 6

Correct answer: C. 6 6 0

Lucas: write n and r in base p and multiply C(nᵢ, rᵢ) digit by digit. 1000 = (2626)₇ and 3 = (0003)₇ → C(2,0)·C(6,0)·C(2,0)·C(6,3) = 20 ≡ 6 (mod 7), which matches the exact value. The factorial formula breaks because 1000! contains 7 as a factor, so it is 0 mod 7, and 3!·997! is also 0 – its 'Fermat inverse' pow(0, p − 2, p) is 0 – so the naive result is 0. Fermat inverses need values coprime to p; for n ≥ p use Lucas.

More Coding Interview Problems questions

Exams that ask this topic