Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Compute 3^(5^20) mod p for the prime p = 10⁹ + 7. By Fermat, exponents can be reduced modulo p − 1 (since gcd(3, p) = 1). Which reduction is valid?

Problem: Compute 3^(5^20) mod p for the prime p = 10⁹ + 7. By Fermat, exponents can be reduced modulo p − 1 (since gcd(3, p) = 1). Which reduction is valid?
MOD = 10**9 + 7
true = pow(3, 5**20, MOD)
print(pow(3, pow(5, 20, MOD - 1), MOD) == true, pow(3, pow(5, 20, MOD), MOD) == true)
What is printed?
  1. A. False True
  2. B. False False
  3. C. True False
  4. D. True True

Correct answer: C. True False

a^(p−1) ≡ 1 (mod p) for a not divisible by p, so a^e ≡ a^(e mod (p−1)). Reducing the exponent mod p (a very common bug in 'power tower' problems) is wrong. Python can verify against the exact 5^20 here, but for towers like a^(b^c) with c ~ 10¹⁸ only the mod-(p−1) reduction is feasible. Each pow is O(log e).

More Coding Interview Problems questions

Exams that ask this topic