Post · 10 min read· pp. 55–60

Euler's totient function

Euler's totient function, also known as phi-function ϕ(n)\phi (n), counts the number of integers between 1 and nn inclusive, which are coprime to nn. Two numbers are coprime if their greatest common divisor equals 11 (11 is considered to be coprime to any number).

Here are values of ϕ(n)\phi(n) for the first few positive integers:

n123456789101112131415161718192021ϕ(n)11224264641041268816618812\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|} \hline n & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15 & 16 & 17 & 18 & 19 & 20 & 21 \\\\ \hline \phi(n) & 1 & 1 & 2 & 2 & 4 & 2 & 6 & 4 & 6 & 4 & 10 & 4 & 12 & 6 & 8 & 8 & 16 & 6 & 18 & 8 & 12 \\\\ \hline \end{array}

Properties

The following properties of Euler totient function are sufficient to calculate it for any number:

  • If pp is a prime number, then gcd⁡(p,q)=1\gcd(p, q) = 1 for all 1≤q<p1 \le q < p. Therefore we have:

ϕ(p)=p−1.\phi (p) = p - 1.

  • If pp is a prime number and k≥1k \ge 1, then there are exactly pk/pp^k / p numbers between 11 and pkp^k that are divisible by pp. Which gives us:

ϕ(pk)=pk−pk−1.\phi(p^k) = p^k - p^{k-1}.

  • If aa and bb are relatively prime, then:

    ϕ(ab)=ϕ(a)⋅ϕ(b).\phi(a b) = \phi(a) \cdot \phi(b).

    This relation is not trivial to see. It follows from the Chinese remainder theorem. The Chinese remainder theorem guarantees, that for each 0≤x<a0 \le x < a and each 0≤y<b0 \le y < b, there exists a unique 0≤z<ab0 \le z < a b with z≡x(moda)z \equiv x \pmod{a} and z≡y(modb)z \equiv y \pmod{b}. It's not hard to show that zz is coprime to aba b if and only if xx is coprime to aa and yy is coprime to bb. Therefore the amount of integers coprime to aba b is equal to product of the amounts of aa and bb.

  • In general, for not coprime aa and bb, the equation

    ϕ(ab)=ϕ(a)⋅ϕ(b)⋅dϕ(d)\phi(ab) = \phi(a) \cdot \phi(b) \cdot \dfrac{d}{\phi(d)}

    with d=gcd⁡(a,b)d = \gcd(a, b) holds.

Thus, using the first three properties, we can compute ϕ(n)\phi(n) through the factorization of nn (decomposition of nn into a product of its prime factors). If n=p1a1⋅p2a2⋯pkakn = {p_1}^{a_1} \cdot {p_2}^{a_2} \cdots {p_k}^{a_k}, where pip_i are prime factors of nn,

ϕ(n)=ϕ(p1a1)⋅ϕ(p2a2)⋯ϕ(pkak)=(p1a1−p1a1−1)⋅(p2a2−p2a2−1)⋯(pkak−pkak−1)=p1a1⋅(1−1p1)⋅p2a2⋅(1−1p2)⋯pkak⋅(1−1pk)=n⋅(1−1p1)⋅(1−1p2)⋯(1−1pk)\begin{align} \phi (n) &= \phi ({p_1}^{a_1}) \cdot \phi ({p_2}^{a_2}) \cdots \phi ({p_k}^{a_k}) \\\\ &= \left({p_1}^{a_1} - {p_1}^{a_1 - 1}\right) \cdot \left({p_2}^{a_2} - {p_2}^{a_2 - 1}\right) \cdots \left({p_k}^{a_k} - {p_k}^{a_k - 1}\right) \\\\ &= p_1^{a_1} \cdot \left(1 - \frac{1}{p_1}\right) \cdot p_2^{a_2} \cdot \left(1 - \frac{1}{p_2}\right) \cdots p_k^{a_k} \cdot \left(1 - \frac{1}{p_k}\right) \\\\ &= n \cdot \left(1 - \frac{1}{p_1}\right) \cdot \left(1 - \frac{1}{p_2}\right) \cdots \left(1 - \frac{1}{p_k}\right) \end{align}

Implementation

Here is an implementation using factorization in O(n)O(\sqrt{n}):

text
int phi(int n) {
    int result = n;
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            while (n % i == 0)
                n /= i;
            result -= result / i;
        }
    }
    if (n > 1)
        result -= result / n;
    return result;
}

Euler totient function from 11 to nn in O(nlog⁡log⁡n)O(n \log\log{n})

If we need the totient of all numbers between 11 and nn, then factorizing all nn numbers is not efficient. We can use the same idea as the Sieve of Eratosthenes. It is still based on the property shown above, but instead of updating the temporary result for each prime factor for each number, we find all prime numbers and for each one update the temporary results of all numbers that are divisible by that prime number.

Since this approach is basically identical to the Sieve of Eratosthenes, the complexity will also be the same: O(nlog⁡log⁡n)O(n \log \log n)

text
void phi_1_to_n(int n) {
    vector<int> phi(n + 1);
    for (int i = 0; i <= n; i++)
        phi[i] = i;

    for (int i = 2; i <= n; i++) {
        if (phi[i] == i) {
            for (int j = i; j <= n; j += i)
                phi[j] -= phi[j] / i;
        }
    }
}

Finding the totient from LL to RR using the segmented sieve

If we need the totient of all numbers between LL and RR, we can use the segmented sieve approach.

The algorithm first precomputes all primes up to R\sqrt{R} using a linear sieve in O(R)O(\sqrt{R}) time and space. For each number in the range [L,R][L, R], it then applies the factorization-based ϕ\phi formula by iterating over these primes. We maintain a remainder array to track the unfactored part of each number. If a remainder is still greater than 1 after processing all small primes, it indicates a large prime factor greater than R\sqrt{R}, which is handled in a final pass. The overall complexity for the range computation is O((R−L+1)log⁡log⁡R)+RO((R - L + 1) \log \log R) + \sqrt{R}.

text
const long long MAX_RANGE = 1e6 + 6;
vector<long long> primes;
long long phi[MAX_RANGE], rem[MAX_RANGE];

vector<int> linear_sieve(int n) { 
    vector<bool> composite(n + 1, 0);
    vector<int> prime;

    // 0 and 1 are not composite (nor prime)
    composite[0] = composite[1] = 1;

    for(int i = 2; i <= n; i++) {
        if(!composite[i]) prime.push_back(i);
        for(int j = 0; j < prime.size() && i * prime[j] <= n; j++) {
            composite[i * prime[j]] = true;
            if(i % prime[j] == 0) break;
        }
    }
    return prime;
}

// To get the value of phi(x) for L <= x <= R, use phi[x - L].
void segmented_phi(long long L, long long R) { 
    for(long long i = L; i <= R; i++) {
        rem[i - L] = i;
        phi[i - L] = i;
    }

    for(long long i : primes) {
        for(long long j = max(i * i, (L + i - 1) / i * i); j <= R; j += i) {
            phi[j - L] -= phi[j - L] / i;
            while(rem[j - L] % i == 0) rem[j - L] /= i;
        }
    }

    for(long long i = 0; i < R - L + 1; i++) {
        if(rem[i] > 1) phi[i] -= phi[i] / rem[i];
    }
}

Divisor sum property

This interesting property was established by Gauss:

∑d∣nϕ(d)=n\sum_{d|n} \phi{(d)} = n

Here the sum is over all positive divisors dd of nn.

For instance the divisors of 10 are 1, 2, 5 and 10. Hence ϕ(1)+ϕ(2)+ϕ(5)+ϕ(10)=1+1+4+4=10\phi{(1)} + \phi{(2)} + \phi{(5)} + \phi{(10)} = 1 + 1 + 4 + 4 = 10.

Finding the totient from 1 to nn using the divisor sum property

The divisor sum property also allows us to compute the totient of all numbers between 1 and nn. This implementation is a little simpler than the previous implementation based on the Sieve of Eratosthenes, however also has a slightly worse complexity: O(nlog⁡n)O(n \log n)

text
void phi_1_to_n(int n) {
    vector<int> phi(n + 1);
    phi[0] = 0;
    phi[1] = 1;
    for (int i = 2; i <= n; i++)
        phi[i] = i - 1;

    for (int i = 2; i <= n; i++)
        for (int j = 2 * i; j <= n; j += i)
              phi[j] -= phi[i];
}

Application in Euler's theorem

The most famous and important property of Euler's totient function is expressed in Euler's theorem:

aϕ(m)≡1(modm)if a and m are relatively prime.a^{\phi(m)} \equiv 1 \pmod m \quad \text{if } a \text{ and } m \text{ are relatively prime.}

In the particular case when mm is prime, Euler's theorem turns into Fermat's little theorem:

am−1≡1(modm)a^{m - 1} \equiv 1 \pmod m

Euler's theorem and Euler's totient function occur quite often in practical applications, for example both are used to compute the modular multiplicative inverse.

As immediate consequence we also get the equivalence:

an≡an mod ϕ(m)(modm)a^n \equiv a^{n \bmod \phi(m)} \pmod m

This allows computing xn mod mx^n \bmod m for very big nn, especially if nn is the result of another computation, as it allows to compute nn under a modulo.

Group Theory

ϕ(n)\phi(n) is the order of the multiplicative group mod n (Z/nZ)×(\mathbb Z / n\mathbb Z)^\times, that is the group of units (elements with multiplicative inverses). The elements with multiplicative inverses are precisely those coprime to nn.

The multiplicative order of an element aa mod nn, denoted ord⁡n(a)\operatorname{ord}_n(a), is the smallest k>0k>0 such that ak≡1(modn)a^k \equiv 1 \pmod n. ord⁡n(a)\operatorname{ord}_n(a) is the size of the subgroup generated by aa, so by Lagrange's Theorem, the multiplicative order of any aa must divide ϕ(n)\phi(n). If the multiplicative order of aa is ϕ(n)\phi(n), the largest possible, then aa is a primitive root and the group is cyclic by definition.

Generalization

There is a less known version of the last equivalence, that allows computing xn mod mx^n \bmod m efficiently for not coprime xx and mm. For arbitrary x,mx, m and n≥log⁡2mn \geq \log_2 m:

xn≡xϕ(m)+[n mod ϕ(m)]mod  mx^{n}\equiv x^{\phi(m)+[n \bmod \phi(m)]} \mod m

Proof:

Let p1,…,ptp_1, \dots, p_t be common prime divisors of xx and mm, and kik_i their exponents in mm. With those we define a=p1k1…ptkta = p_1^{k_1} \dots p_t^{k_t}, which makes ma\frac{m}{a} coprime to xx. And let kk be the smallest number such that aa divides xkx^k. Assuming n≥kn \ge k, we can write:

xn mod m=xkaaxn−k mod m=xka(axn−k mod m) mod m=xka(axn−k mod ama) mod m=xkaa(xn−k mod ma) mod m=xk(xn−k mod ma) mod m\begin{align}x^n \bmod m &= \frac{x^k}{a}ax^{n-k}\bmod m \\ &= \frac{x^k}{a}\left(ax^{n-k}\bmod m\right) \bmod m \\ &= \frac{x^k}{a}\left(ax^{n-k}\bmod a \frac{m}{a}\right) \bmod m \\ &=\frac{x^k}{a} a \left(x^{n-k} \bmod \frac{m}{a}\right)\bmod m \\ &= x^k\left(x^{n-k} \bmod \frac{m}{a}\right)\bmod m \end{align}

The equivalence between the third and forth line follows from the fact that ab mod ac=a(b mod c)ab \bmod ac = a(b \bmod c). Indeed if b=cd+rb = cd + r with r<cr < c, then ab=acd+arab = acd + ar with ar<acar < ac.

Since xx and ma\frac{m}{a} are coprime, we can apply Euler's theorem and get the efficient (since kk is very small; in fact k≤log⁡2mk \le \log_2 m) formula:

xn mod m=xk(xn−k mod ϕ(ma) mod ma) mod m.x^n \bmod m = x^k\left(x^{n-k \bmod \phi(\frac{m}{a})} \bmod \frac{m}{a}\right)\bmod m.

This formula is difficult to apply, but we can use it to analyze the behavior of xn mod mx^n \bmod m. We can see that the sequence of powers (x1 mod m,x2 mod m,x3 mod m,… )(x^1 \bmod m, x^2 \bmod m, x^3 \bmod m, \dots) enters a cycle of length ϕ(ma)\phi\left(\frac{m}{a}\right) after the first kk (or less) elements. ϕ(ma)\phi\left(\frac{m}{a}\right) divides ϕ(m)\phi(m) (because aa and ma\frac{m}{a} are coprime we have ϕ(a)⋅ϕ(ma)=ϕ(m)\phi(a) \cdot \phi\left(\frac{m}{a}\right) = \phi(m)), therefore we can also say that the period has length ϕ(m)\phi(m). And since ϕ(m)≥log⁡2m≥k\phi(m) \ge \log_2 m \ge k, we can conclude the desired, much simpler, formula:

xn≡xϕ(m)x(n−ϕ(m)) mod ϕ(m) mod m≡xϕ(m)+[n mod ϕ(m)]mod  m.x^n \equiv x^{\phi(m)} x^{(n - \phi(m)) \bmod \phi(m)} \bmod m \equiv x^{\phi(m)+[n \bmod \phi(m)]} \mod m.

Practice Problems