Algorithms · Visualized
Number Theory: Euler Totient
Number Theory
Divisibility, primes, hashes and modular arithmetic — the math underneath algorithms.
Euler's totient φ(k) counts how many integers from 1 to k are coprime to k (share no common factor other than 1). Time: O(√k) per single value average, O(n√n) worst; space: O(n) to store the results (O(1) per query).
Big-O: GCD O(log min(a,b)); sieve O(n log log n).
Euler Totient Function
Number TheoryEuler's totient φ(k) counts how many integers from 1 to k are coprime to k (share no common factor other than 1). The trick: factorize k, then apply the formula φ(k) = k · ∏(1 − 1/p) over its distinct prime factors — each prime p 'removes' exactly a 1/p fraction of the remaining candidates.
How Euler Totient Works
- Set result = k and let m = k — m will be shrunk by dividing out prime factors.
- For every candidate prime p from 2 up to √m: if p divides m, it is a prime factor of k.
- Divide m by p as many times as possible (remove that prime completely), then update result −= result / p.
- If after the loop m is still greater than 1, one large prime factor remains — apply result −= result / m for it too.
- The final result is φ(k). Repeat for k = 1..n to build the whole totient table.
Euler Totient Worked Example
Input: 12
φ(1)=1. φ(12): factors {2,3} → 12·(1−1/2)·(1−1/3) = 4 → coprimes {1,5,7,11}. φ(13): 13 is prime → 13−1 = 12. Continuing gives [1,1,2,2,4,2,6,4,6,4,10,4] for k=1..12.
def phi(k):
result, m = k, k
p = 2
while p * p <= m:
if m % p == 0: # p is a prime factor
while m % p == 0:
m //= p
result -= result // p # k · ∏(1 − 1/p)
p += 1
if m > 1: # leftover large prime
result -= result // m
return resultBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Euler Totient Time & Space Complexity
When to Use Euler Totient
- Modular arithmetic: Euler's theorem uses φ(m) to compute huge powers under a modulus.
- Counting reduced fractions and primitive roots; a building block in RSA-style cryptography math.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.