Euler's Totient Function Explained — Phi(n) Computation, Sieve Variant in O(N log log N) [Cryptography, Google]
Advertisement
Algorithm Statement
Euler's totient function counts the positive integers up to that are coprime to : \varphi(n) = |\\{k : 1 \le k \le n, \ \gcd(k, n) = 1\\}|.
Two regimes:
- Single value: factor and apply in .
- All values up to : sieve in similar to the Eratosthenes sieve.
Constraints:
- for single value.
- for the sieve variant.
Examples:
phi(1) = 1
phi(9) = 6 (coprime: 1, 2, 4, 5, 7, 8)
phi(10) = 4 (coprime: 1, 3, 7, 9)
phi(36) = 12 (n=36 = 2^2 * 3^2 → 36 * (1/2) * (2/3))Why This Problem Matters
Euler's totient function appears in three high-leverage interview contexts:
- Cryptography. RSA encryption uses where is the product of two primes; the security reduces to factoring .
- Modular inverse for composite moduli. Euler's theorem says when . So , which extends Fermat to composite .
- Counting coprime pairs. Problems like LeetCode "Coprime Pairs in a Tree", or Codeforces problems counting fractions in lowest terms, all reduce to summations of .
Google has used in distributed-systems interviews to derive the period of pseudo-random generators. Competitive programmers see it constantly in problems involving the Mobius function, divisor-sum identities, and the multiplicative inverse mod a non-prime.
The Core Insight
Multiplicativity. is a multiplicative function: if , then . This reduces to its values on prime powers.
On a prime power. . Reasoning: among , the multiples of are , exactly of them. The rest are coprime to .
General formula. Combining:
For example, .
Sieve construction. Initialize phi[i] = i for all . For each prime (detected when phi[p] == p), iterate over multiples and update phi[m] -= phi[m] / p. This is the same as multiplying by , but using only integer arithmetic. Each composite gets touched once per distinct prime factor, so the total work is .
Proof of Euler's product formula. Let . Inclusion-exclusion over the primes dividing : count integers divisible by none of . The result simplifies to .
Visual Dry Run
Compute via the formula. .
phi(60) = 60 * (1 - 1/2) * (1 - 1/3) * (1 - 1/5)
= 60 * 1/2 * 2/3 * 4/5
= 60 * 8/30
= 16
Coprime check: count k in [1, 60] with gcd(k, 60) = 1.
{1, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 49, 53, 59}
That is 16 values. Confirms phi(60) = 16.Sieve up to .
Initial: phi = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
p = 2 (phi[2] == 2 → prime)
for m in 2,4,6,8,10:
phi[m] -= phi[m] / 2
phi[2] = 2 - 1 = 1
phi[4] = 4 - 2 = 2
phi[6] = 6 - 3 = 3
phi[8] = 8 - 4 = 4
phi[10] = 10 - 5 = 5
p = 3 (phi[3] == 3 → prime)
phi[3] = 3 - 1 = 2
phi[6] = 3 - 1 = 2
phi[9] = 9 - 3 = 6
p = 5 (phi[5] == 5 → prime)
phi[5] = 5 - 1 = 4
phi[10] = 5 - 1 = 4
p = 7 (phi[7] == 7 → prime)
phi[7] = 7 - 1 = 6
Final: phi = [0, 1, 1, 2, 2, 4, 2, 6, 4, 6, 4]Verify: (coprime: 1, 5). (coprime: 1, 3, 7, 9). Correct.
Solution (Optimal)
Python — Single Value
def phi(n: int) -> int:
"""Compute Euler's totient phi(n) in O(sqrt n)."""
result = n
p = 2
while p * p <= n:
if n % p == 0:
while n % p == 0:
n //= p
result -= result // p
p += 1
if n > 1:
result -= result // n # leftover prime factor
return resultComplexity: time, extra space.
Python — Sieve up to N
def phi_sieve(N: int) -> list[int]:
phi = list(range(N + 1))
for p in range(2, N + 1):
if phi[p] == p: # p is prime
for m in range(p, N + 1, p):
phi[m] -= phi[m] // p
return phiComplexity: time, space.
JavaScript — Single Value
function phi(n) {
let result = n;
for (let p = 2; p * p <= n; p++) {
if (n % p === 0) {
while (n % p === 0) n = Math.floor(n / p);
result -= Math.floor(result / p);
}
}
if (n > 1) result -= Math.floor(result / n);
return result;
}JavaScript — Sieve
function phiSieve(N) {
const phi = Array.from({ length: N + 1 }, (_, i) => i);
for (let p = 2; p <= N; p++) {
if (phi[p] === p) {
for (let m = p; m <= N; m += p) {
phi[m] -= Math.floor(phi[m] / p);
}
}
}
return phi;
}Common Mistakes
- Multiplying by in floats. Floating-point rounding gives the wrong integer answer. Always use the integer rewrite
result -= result / p. - Reducing by every divisor instead of every prime divisor. The product runs over distinct prime divisors only.
- Forgetting the leftover prime. After the trial-division loop, if the residual then itself is a prime factor.
- Wrong base case. , not 0. The single value is coprime to itself by convention.
- Using Fermat for inverse mod composite. Fermat requires the modulus to be prime. For composite , use (provided ).
- Order of operations in the sieve. Update
phi[m] -= phi[m] / ponly before processing higher primes; the SPF-style sieve traversal order matters.
Interview Tips
- State the multiplicativity of early: " when ." Interviewers respect when you reach for structure.
- For RSA-flavored questions, mention Carmichael's if asked — it is the smaller exponent that suffices for .
- For sums like (Euler's identity), cite it directly to save derivation time.
- If the problem is "count coprime pairs with ", the answer is . Memorize that.
Follow-up Questions
Q1: Compute when is composite and . A: Use . Or use Extended Euclidean — usually faster in practice because it does not require factoring .
Q2: Show that . A: Group the integers by the value of . For each divisor of , exactly integers have . Sum over .
Q3: Compute for all values up to in optimal time. A: Use the linear sieve, which extends the SPF sieve to compute in .
Q4: Apply to count fractions in lowest terms with denominator . A: The Farey sequence count is , computable in with the sieve.
Key Takeaways
- counts integers in coprime to , with the closed form .
- Multiplicativity when reduces every computation to prime powers.
- The sieve variant runs in by initializing
phi[i] = ithen peeling off each prime viaphi[m] -= phi[m] / p. - Euler's theorem generalizes Fermat: when , enabling modular inverse for composite moduli.
- The identity underpins divisor-sum problems and Mobius inversion.
- is the bridge between number theory and cryptography (RSA, ElGamal) and competitive-programming counting problems.
Advertisement