Data Structures & AlgorithmsHardProduct company OA
Problem: Euler's totient φ(n) counts integers in 1..n coprime to n: φ(n) = n · Π (1 − 1/p) over distinct primes p dividing n, computed by trial division.
Problem: Euler's totient φ(n) counts integers in 1..n coprime to n: φ(n) = n · Π (1 − 1/p) over distinct primes p dividing n, computed by trial division.
def phi(n):
res, p = n, 2
while p * p <= n:
if n % p == 0:
while n % p == 0: n //= p
res -= res // p
p += 1
if n > 1: res -= res // n
return res
print(phi(36), phi(97), phi(100))What is printed?- A. 12 97 40
- B. 12 96 40
- C. 12 96 60
- D. 24 96 40
Correct answer: B. 12 96 40
36 = 2²·3² → 36 · ½ · ⅔ = 12 (1, 5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35). A prime p gives p − 1 = 96. 100 = 2²·5² → 100 · ½ · ⅘ = 40. 'res −= res // p' applies (1 − 1/p) exactly in integers; forgetting the leftover prime factor > √n (the final if) is a classic bug. O(√n).
More Coding Interview Problems questions
- Problem: Find the maximum product len(w1) · len(w2) over pairs of words that share no letter, using a 26-bit letter mask per word. python…
- Problem: Sum (a[i] XOR a[j]) over all pairs i < j in O(n · bits): at bit b, a pair contributes 2^b exactly when one value has the bit and…
- Problem: Count triples (i, j, k) with i < j ≤ k such that XOR(a[i..j−1]) == XOR(a[j..k]). This holds iff XOR(a[i..k]) = 0, i.e. prefix[i]…
- Problem: Write an integer in base −2 (digits 0/1, place values 1, −2, 4, −8, …). When Python's divmod by −2 gives a negative remainder…
- Problem: Convert a fraction to a decimal string, putting a repeating part in parentheses: remember at which output position each remainder…
- Problem: Fibonacci numbers modulo m repeat with the Pisano period π(m). Use it to get F(10¹⁸) mod 10 without big loops. python def…