Algorithm Search⌘K

Proofs: Euler totient sieve

These are the human proofs of Euler totient sieve, at full length.

The totient sieve computes phi(m) for every m up to n full

This proof shows: correctness.

For 1≤m≤n1 \le m \le n and an integer t≥2t \ge 2 let

Ft(m)=m∏q prime, q<t, q∣mq−1q.F_t(m) = m \prod_{q \text{ prime},\ q < t,\ q \mid m} \frac{q - 1}{q}.

So F2(m)=mF_2(m) = m, and Ft(m)=φ(m)F_t(m) = \varphi(m) as soon as tt exceeds every prime factor of mm, by the product formula φ(m)=m∏q∣m(1−1/q)\varphi(m) = m \prod_{q \mid m} (1 - 1/q).

Lemma 1. Ft(m)F_t(m) is an integer. If p≥tp \ge t is a prime that divides mm, then pp divides Ft(m)F_t(m).

Proof. Let QQ be the product of the distinct primes q<tq < t that divide mm. Then Q∣mQ \mid m and Ft(m)=(m/Q)∏q∣Q(q−1)F_t(m) = (m / Q) \prod_{q \mid Q} (q - 1), an integer. If p≥tp \ge t is prime and p∣mp \mid m, then p∤Qp \nmid Q, so pp divides m/Qm / Q and therefore Ft(m)F_t(m). □\square

Invariant. Each time the loop of line L2 reaches a value pp (with 2≤p≤n+12 \le p \le n + 1, where p=n+1p = n + 1 means the loop has ended), for every 1≤m≤n1 \le m \le n:

(I) φ[m]=Fp(m)\varphi[m] = F_p(m).

Initialization. Line L1 sets φ[m]=m=F2(m)\varphi[m] = m = F_2(m).

The test of line L3. Let 2≤p≤n2 \le p \le n and assume (I). If pp is prime, no prime q<pq < p divides pp, so φ[p]=Fp(p)=p\varphi[p] = F_p(p) = p. If pp is composite, it has a prime factor q<pq < p, and Fp(p)≤p(q−1)/q<pF_p(p) \le p (q - 1)/q < p. So line L3 succeeds exactly when pp is prime.

Maintenance. If pp is composite, no entry changes, and Fp+1(m)=Fp(m)F_{p+1}(m) = F_p(m) for all mm, because the prime condition q<p+1q < p + 1 adds only q=pq = p, which is not prime. If pp is prime, lines L4 and L5 visit exactly the multiples mm of pp with m≤nm \le n, each once. For such mm, Lemma 1 (with t=pt = p) says that pp divides φ[m]=Fp(m)\varphi[m] = F_p(m), so line L5 computes exactly

Fp(m)−Fp(m)p=Fp(m)⋅p−1p=Fp+1(m).F_p(m) - \frac{F_p(m)}{p} = F_p(m) \cdot \frac{p - 1}{p} = F_{p+1}(m).

For mm not divisible by pp, the entry does not change, and Fp+1(m)=Fp(m)F_{p+1}(m) = F_p(m). So (I) holds for p+1p + 1.

Termination. The outer loop runs n−1n - 1 times, and each inner loop at most n/pn/p times.

Conclusion. When the loop ends, p=n+1p = n + 1. Every prime factor of m≤nm \le n is at most n<n+1n < n + 1, so φ[m]=Fn+1(m)=φ(m)\varphi[m] = F_{n+1}(m) = \varphi(m) for every 1≤m≤n1 \le m \le n. Line L1 sets φ[0]=0\varphi[0] = 0, and no later line writes to index 0. ■\blacksquare

The number of updates. For each prime p≤np \le n, line L5 runs once for each of the ⌊n/p⌋\lfloor n/p \rfloor multiples of pp in [1,n][1, n]. Since n/p−1<⌊n/p⌋≤n/pn/p - 1 < \lfloor n/p \rfloor \le n/p and π(n)≤n\pi(n) \le n, the total is n∑p≤n1/p+O(n)n \sum_{p \le n} 1/p + O(n), and Mertens' theorem gives nln⁡ln⁡n+O(n)n \ln \ln n + O(n).

Back to Euler totient sieve