Algorithm Search⌘K

Proofs: Sieve of Sundaram

These are the human proofs of Sieve of Sundaram, at full length.

The sieve of Sundaram returns exactly the primes up to n full

This proof shows: correctness.

For n<2n < 2 there is no prime p≤np \le n, and line L1 returns the empty list. Let n≥2n \ge 2 and k=⌊(n−1)/2⌋k = \lfloor (n-1)/2 \rfloor. The map x↦2x+1x \mapsto 2x + 1 is a bijection from {1,…,k}\{1, \ldots, k\} onto the odd numbers mm with 3≤m≤n3 \le m \le n: indeed 2x+1≤n2x + 1 \le n exactly when x≤(n−1)/2x \le (n-1)/2, that is, when x≤kx \le k.

Lemma 1. For x≥1x \ge 1, the odd number 2x+12x + 1 is composite if and only if x=i+j+2ijx = i + j + 2ij for some integers 1≤i≤j1 \le i \le j.

Proof. The identity 2(i+j+2ij)+1=(2i+1)(2j+1)2(i + j + 2ij) + 1 = (2i+1)(2j+1) holds for all integers. If x=i+j+2ijx = i + j + 2ij with 1≤i≤j1 \le i \le j, then 2x+12x + 1 is the product of two integers that are at least 3, so it is composite. Conversely, if the odd number m=2x+1m = 2x + 1 is composite, write m=abm = ab with 1<a≤b1 < a \le b. Both factors are odd, because mm is odd, so a=2i+1a = 2i + 1 and b=2j+1b = 2j + 1 with 1≤i≤j1 \le i \le j. Then 2x+1=(2i+1)(2j+1)=2(i+j+2ij)+12x + 1 = (2i+1)(2j+1) = 2(i + j + 2ij) + 1, so x=i+j+2ijx = i + j + 2ij. □\square

Lemma 2. After the loop of line L5 ends, for every xx with 1≤x≤k1 \le x \le k, M[x]M[x] is true if and only if x=i+j+2ijx = i + j + 2ij for some 1≤i≤j1 \le i \le j.

Proof. Line L3 sets every M[x]M[x] to false, and line L8 is the only line that writes to MM; it writes true, at the index i+j+2iji + j + 2ij for the current ii and jj. The inner loop starts at j=ij = i (line L6) and runs while the index is at most kk, so each written index is of the stated form with 1≤i≤j1 \le i \le j and lies in 1…k1 \ldots k.

Conversely, take 1≤i≤j1 \le i \le j with x=i+j+2ij≤kx = i + j + 2ij \le k. The function fi(j)=i+j+2ijf_i(j) = i + j + 2ij grows strictly with jj, so fi(i)=2i+2i2≤fi(j)≤kf_i(i) = 2i + 2i^2 \le f_i(j) \le k, and the test of line L5 holds for this ii. The outer loop takes the values i=1,2,…i = 1, 2, \ldots in order and stops at the first ii that fails line L5; since fi(i)f_i(i) grows with ii, every ii with fi(i)≤kf_i(i) \le k is reached. For this ii, the inner loop takes j=i,i+1,…j = i, i + 1, \ldots and stops at the first jj with fi(j)>kf_i(j) > k; since fif_i grows, it reaches our jj, and line L8 sets M[x]M[x] to true. □\square

Termination. For each ii the inner loop runs at most kk times, since fi(j)≥jf_i(j) \ge j. The outer loop runs at most kk times, since fi(i)≥if_i(i) \ge i.

Conclusion. By Lemmas 1 and 2, for 1≤x≤k1 \le x \le k the flag M[x]M[x] is false exactly when 2x+12x + 1 is an odd prime. By the bijection above, line L11 returns 2 followed by every odd prime m≤nm \le n, in increasing order. Since every prime other than 2 is odd and 2≤n2 \le n, this is the list of all primes up to nn. ■\blacksquare

Back to Sieve of Sundaram