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?
  1. A. 12 97 40
  2. B. 12 96 40
  3. C. 12 96 60
  4. 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

Exams that ask this topic