Proofs: Trial division
These are the human proofs of Trial division, at full length.
Trial division returns the prime factorization full
This proof shows: correctness, termination.
Let . We write for the product of the entries of the list (the empty product is ). The trial divisors that line L5 produces are , , , and in general for . Each integer that is not one of them is even and larger than .
Invariant. Each time line L2 tests its condition:
(T1) and . (T2) Each entry of is a prime less than , and the entries are in non-decreasing order. (T3) No prime divides .
Initialization. Line L1 sets empty, and . Then (T1) holds because , (T2) is empty, and (T3) holds because there is no prime less than .
The inner loop. Fix one pass of the outer loop, with divisor . We claim that each time line L3 finds , is prime. Let be a prime factor of . Then , and by (T3) . Since , we get , so is prime. Line L4 then appends and divides by . This keeps , keeps , and keeps in order, because each earlier entry is less than by (T2). The inner loop stops after finitely many steps, since drops by a factor in each step and stays at least . When it stops, .
Maintenance. Let be the next divisor from line L5. (T1) holds by the inner loop. Each entry of is at most , so (T2) holds. For (T3), let be a prime. If , then by (T3) before the pass, and dividing cannot add a prime factor. If , then because the inner loop ended. If , then is not a trial divisor, so is even and larger than , which is not a prime. So no such exists, and (T3) holds for .
Termination. In each pass, grows by at least , and does not grow. So after at most passes, , and the test of line L2 fails.
The result. When line L2 fails, . Assume that is composite. Then with , so , and a prime factor of is a prime less than that divides . This contradicts (T3). So or is prime. If is prime, then by (T3), so is at least each entry of by (T2), and line L6 appends it at the end in order. In both cases the list that line L7 returns holds primes in non-decreasing order with , by (T1). By the uniqueness of the factorization, this is the prime factorization of .