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?
- A. False True
- B. False False
- C. True False
- 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
- Problem: Two equal-length strings over {x, y}; one move swaps s1[i] with s2[j] (any i, j). Minimum moves to make them equal (−1 if…
- Problem: Rabin–Karp search with a rolling hash: (a) base 10, modulus 7; (b) base 256, modulus 1000003. Count true matches and spurious…
- Problem: A primality helper tries divisors while i·i ≤ n. How many loop iterations run for n = 10⁶ and for n = 99, and what is the…
- Problem: Find the bug: version numbers stored as strings are sorted to find the smallest. What does each sort produce? python…
- Problem: What is the time complexity of this nested loop, and how many inner steps run for n = 1024? python def cnt(n): c = 0 for i in…
- Problem: Find the bug: a backtracking routine collects all subsets of [1, 2]. python def subsets(a): res, path = [], [] def bt(i): if i ==…