Proofs: Wheel factorization
These are the human proofs of Wheel factorization, at full length.
Correctness of wheel factorization full
This proof shows: correctness, termination.
Let , let be the first primes, (with for ), and let be the least integer greater than with .
Lemma 1 (the wheel lists the right numbers). The values that takes at line L5 are exactly the integers with , in increasing order.
Proof. Since , the set is invariant under . Its elements in are , where . So the elements of in increasing order are , and the gap from each to the next is for and at the end of a period. Line L4 sets , , and line L7 adds and advances modulo ; by induction, after steps is the -th element of (counted from ) and .
Lemma 2. Every prime that is not a wheel prime is in , and every prime less than is a wheel prime.
Proof. A prime that is not among does not divide , so . As , the minimality of gives , so . The second claim is the contrapositive.
Invariant. Each time line L5 is reached: (a) ; (b) is a list of primes in non-decreasing order, each less than ; (c) no prime less than divides .
Initialization. After lines L1 to L3, holds each wheel prime as often as it divides , in increasing order, and , so (a) holds and has no wheel prime as a factor. Line L4 sets . Each wheel prime is less than (it divides , so it is not coprime to , and the primes are less than when the basis is the first primes). So (b) holds. Every prime less than is a wheel prime by Lemma 2, so (c) holds.
Maintenance. Suppose the invariant holds and . First, if , then is prime: , and a prime factor of divides , so by (c), which forces . The inner loop of line L6 divides by while possible and appends each time, which keeps (a), keeps the order in (b) because every earlier entry is less than , and leaves . Line L7 moves to , the next element of (Lemma 1). The entries of are at most , so (b) holds. For (c), let be a prime. If is a wheel prime, it does not divide (it was removed in lines L2 and L3, and only shrinks by other factors). Otherwise by Lemma 2, and means since no element of lies strictly between and . If , (c) before the step gives ; if , line L6 removed it. Dividing never adds prime factors, so (c) holds for the new .
Termination. Each pass of the outer loop increases by a positive gap, and never grows. So after finitely many passes . Each inner loop of line L6 ends, because and is a positive integer that shrinks with each division.
Correctness. When the loop stops, . If were composite, it would have a prime factor , against (c). So or is a prime with by (c); in the second case line L8 appends , which is at least every entry of . By (a), the product of the returned list is , and every entry is prime and in non-decreasing order. By the fundamental theorem of arithmetic this is the factorization of .