Proofs: Segmented sieve
These are the human proofs of Segmented sieve, at full length.
The segmented sieve returns exactly the primes in [L, R] full
This proof shows: correctness.
For let be the least prime factor of . Recall that a composite satisfies : writing with , every prime factor of divides and so is at least , which gives .
After line L1, . If , there is no integer in and the empty answer is correct; this covers . From now on . Line L2 is the sieve of Eratosthenes, so base is the increasing list of all primes , that is, all primes with .
The blocks. Line L3 sets . Each pass of the loop of line L4 handles the block with , since and , and line L11 sets the next to . So the blocks are , consecutive, disjoint and in increasing order, and each has at least one number. The loop stops at the first ; since grows by at least 1 in each pass, it stops, and the last block ends at . So the blocks cover exactly.
One block. Fix a block with . Line L6 sets every flag to true, and only line L9 changes a flag, always to false. We show that after line L9 is done, for , the flag is false if and only if is composite.
Only composites are cleared. Line L9 clears for a base prime and an integer , where from line L8 is a multiple of with . So is a multiple of and ; such an has the proper divisor and is composite.
Every composite is cleared. Let in be composite and . Then , so is a base prime, and , so line L7 handles . Line L8 sets . Both terms are multiples of . The number is the least multiple of that is at least , so it is at most ; also . Hence , and is a multiple of , as both are. So for some , and since , the loop of line L9 reaches and clears its flag.
Line L8 is well defined. is computed in integers as ; nothing else is needed.
So line L10 appends exactly the primes of , in increasing order of .
Termination of one block. Line L7 runs over a finite list, and line L9 advances by until it passes .
Conclusion. The blocks partition in increasing order, and each block appends its primes in increasing order. So the list returned in line L12 is the increasing list of all primes with .
Cost of marking. For a base prime and a block of length , line L9 runs at most times, since its values are distinct multiples of in an interval of length . Summing over the blocks and the base primes gives the bound in the complexity section.