Proofs: Sieve of Eratosthenes
These are the human proofs of Sieve of Eratosthenes, at full length.
The sieve of Eratosthenes returns exactly the primes up to n full
This proof shows: correctness.
For there is no prime , and line L1 returns the empty list. From now on . For an integer let be its smallest prime factor. We use two facts.
Fact 1. If is composite, then . Indeed with and . Each prime factor of divides , so it is at least , and therefore and .
Fact 2. If is composite and , then with . This is the same argument.
Invariant. Each time line L4 tests a value , the following holds for every with :
(I) is false if and only if is composite and .
Initialization. Line L3 sets . Line L2 sets every with to true, and no has . So (I) holds.
Line L5 tests primality. Suppose line L4 lets through, so and . If is composite, then by Fact 1, , so by (I), is false. If is prime, then is not composite, so by (I), is true. Hence the test of line L5 succeeds exactly when is prime.
Maintenance. We show that (I) holds for after line L8.
- If is composite, lines L6 and L7 do not run and no flag changes. No integer has , since is prime. So " composite and " is the same as " composite and ", and (I) holds for .
- If is prime, lines L6 and L7 set to false for exactly the numbers with and . Each such is composite, because , and . Conversely, let be composite with . By Fact 2, with , so the loop clears . No flag is set back to true. So after the loop, is false exactly when is composite with (cleared before, by (I)) or composite with (cleared now). This is (I) for .
Termination. The value grows by one in each pass of the loop, so the test of line L4 fails after at most passes. Each loop of line L6 is finite, since grows by and stops above .
Conclusion. When line L4 fails, , so . Let . If is prime, it is not composite, so by (I), is true. If is composite, then by Fact 1, , so by (I), is false. So is true exactly for the primes in , and line L9 returns all primes up to in increasing order.
The count of writes. For a prime with , the loop of line L6 visits for , which is values. Summed over these primes, this is the formula for in the complexity section. The lower bound uses and , so , and Mertens' theorem makes this .