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 there is no prime , and line L1 returns the empty list. Let and . The map is a bijection from onto the odd numbers with : indeed exactly when , that is, when .
Lemma 1. For , the odd number is composite if and only if for some integers .
Proof. The identity holds for all integers. If with , then is the product of two integers that are at least 3, so it is composite. Conversely, if the odd number is composite, write with . Both factors are odd, because is odd, so and with . Then , so .
Lemma 2. After the loop of line L5 ends, for every with , is true if and only if for some .
Proof. Line L3 sets every to false, and line L8 is the only line that writes to ; it writes true, at the index for the current and . The inner loop starts at (line L6) and runs while the index is at most , so each written index is of the stated form with and lies in .
Conversely, take with . The function grows strictly with , so , and the test of line L5 holds for this . The outer loop takes the values in order and stops at the first that fails line L5; since grows with , every with is reached. For this , the inner loop takes and stops at the first with ; since grows, it reaches our , and line L8 sets to true.
Termination. For each the inner loop runs at most times, since . The outer loop runs at most times, since .
Conclusion. By Lemmas 1 and 2, for the flag is false exactly when is an odd prime. By the bijection above, line L11 returns 2 followed by every odd prime , in increasing order. Since every prime other than 2 is odd and , this is the list of all primes up to .