The totient sieve computes phi(m) for every m up to n full
This proof shows: correctness.
For 1≤m≤n and an integer t≥2 let
Ft(m)=mq prime, q<t, q∣m∏qq−1. So F2(m)=m, and Ft(m)=φ(m) as soon as t exceeds every prime factor of m, by the product formula φ(m)=m∏q∣m(1−1/q).
Lemma 1. Ft(m) is an integer. If p≥t is a prime that divides m, then p divides Ft(m).
Proof. Let Q be the product of the distinct primes q<t that divide m. Then Q∣m and Ft(m)=(m/Q)∏q∣Q(q−1), an integer. If p≥t is prime and p∣m, then p∤Q, so p divides m/Q and therefore Ft(m). □
Invariant. Each time the loop of line L2 reaches a value p (with 2≤p≤n+1, where p=n+1 means the loop has ended), for every 1≤m≤n:
(I) φ[m]=Fp(m).
Initialization. Line L1 sets φ[m]=m=F2(m).
The test of line L3. Let 2≤p≤n and assume (I). If p is prime, no prime q<p divides p, so φ[p]=Fp(p)=p. If p is composite, it has a prime factor q<p, and Fp(p)≤p(q−1)/q<p. So line L3 succeeds exactly when p is prime.
Maintenance. If p is composite, no entry changes, and Fp+1(m)=Fp(m) for all m, because the prime condition q<p+1 adds only q=p, which is not prime. If p is prime, lines L4 and L5 visit exactly the multiples m of p with m≤n, each once. For such m, Lemma 1 (with t=p) says that p divides φ[m]=Fp(m), so line L5 computes exactly
Fp(m)−pFp(m)=Fp(m)⋅pp−1=Fp+1(m). For m not divisible by p, the entry does not change, and Fp+1(m)=Fp(m). So (I) holds for p+1.
Termination. The outer loop runs n−1 times, and each inner loop at most n/p times.
Conclusion. When the loop ends, p=n+1. Every prime factor of m≤n is at most n<n+1, so φ[m]=Fn+1(m)=φ(m) for every 1≤m≤n. Line L1 sets φ[0]=0, and no later line writes to index 0. ■
The number of updates. For each prime p≤n, line L5 runs once for each of the ⌊n/p⌋ multiples of p in [1,n]. Since n/p−1<⌊n/p⌋≤n/p and π(n)≤n, the total is n∑p≤n1/p+O(n), and Mertens' theorem gives nlnlnn+O(n).