Number theory & mathAnimated
Euler's Totient Function
Count of numbers ≤ n that are coprime to n.
Time
O(√n)
Extra space
O(1)
Use it for
RSA, modular inverses.
How it works
- φ(n) counts the numbers from 1 to n that share no factor with n (are coprime to n).
- Formula: φ(n) = n × ∏ (1 − 1/p) over each distinct prime p dividing n.
- Find the distinct primes of n, and for each one multiply the running result by (p − 1)/p.
- We also count coprimes by brute force to double-check.
Watch it run
Loading animation…