Algorithm Search⌘K

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 N≥1N \ge 1. We write ∏F\prod F for the product of the entries of the list FF (the empty product is 11). The trial divisors that line L5 produces are d0=2d_0 = 2, d1=3d_1 = 3, d2=5d_2 = 5, and in general dj=2j+1d_j = 2j + 1 for j≥1j \ge 1. Each integer c≥2c \ge 2 that is not one of them is even and larger than 22.

Invariant. Each time line L2 tests its condition:

(T1) N=(∏F)⋅mN = (\prod F) \cdot m and m≥1m \ge 1. (T2) Each entry of FF is a prime less than dd, and the entries are in non-decreasing order. (T3) No prime q<dq < d divides mm.

Initialization. Line L1 sets FF empty, m=Nm = N and d=2d = 2. Then (T1) holds because N≥1N \ge 1, (T2) is empty, and (T3) holds because there is no prime less than 22.

The inner loop. Fix one pass of the outer loop, with divisor dd. We claim that each time line L3 finds d∣md \mid m, dd is prime. Let qq be a prime factor of dd. Then q∣mq \mid m, and by (T3) q≥dq \ge d. Since q≤dq \le d, we get q=dq = d, so dd is prime. Line L4 then appends dd and divides mm by dd. This keeps N=(∏F)⋅mN = (\prod F) \cdot m, keeps m≥1m \ge 1, and keeps FF in order, because each earlier entry is less than dd by (T2). The inner loop stops after finitely many steps, since mm drops by a factor d≥2d \ge 2 in each step and stays at least 11. When it stops, d∤md \nmid m.

Maintenance. Let d′d' be the next divisor from line L5. (T1) holds by the inner loop. Each entry of FF is at most d<d′d < d', so (T2) holds. For (T3), let q<d′q < d' be a prime. If q<dq < d, then q∤mq \nmid m by (T3) before the pass, and dividing mm cannot add a prime factor. If q=dq = d, then q∤mq \nmid m because the inner loop ended. If d<q<d′d < q < d', then qq is not a trial divisor, so qq is even and larger than 22, which is not a prime. So no such qq exists, and (T3) holds for d′d'.

Termination. In each pass, dd grows by at least 11, and mm does not grow. So after at most ⌊N⌋\lfloor \sqrt{N} \rfloor passes, d⋅d>N≥md \cdot d > N \ge m, and the test of line L2 fails.

The result. When line L2 fails, d2>md^2 > m. Assume that mm is composite. Then m=abm = ab with 1<a≤b1 < a \le b, so a≤m<da \le \sqrt{m} < d, and a prime factor of aa is a prime less than dd that divides mm. This contradicts (T3). So m=1m = 1 or mm is prime. If mm is prime, then m≥dm \ge d by (T3), so mm is at least each entry of FF by (T2), and line L6 appends it at the end in order. In both cases the list FF that line L7 returns holds primes in non-decreasing order with ∏F=N\prod F = N, by (T1). By the uniqueness of the factorization, this is the prime factorization of NN. ■\blacksquare

Back to Trial division