Skip to content
StackDecode
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

  1. φ(n) counts the numbers from 1 to n that share no factor with n (are coprime to n).
  2. Formula: φ(n) = n × ∏ (1 − 1/p) over each distinct prime p dividing n.
  3. Find the distinct primes of n, and for each one multiply the running result by (p − 1)/p.
  4. We also count coprimes by brute force to double-check.

Watch it run

Loading animation…