Correctness of the modular linear equation solver full
This proof shows: correctness, termination, sorted-output.
Let a, b be integers and n≥1. Write S={x∈Z:n∣ax−b} for the set of integer solutions. We prove that MODULAR-LINEAR-EQUATION-SOLVER(a,b,n) terminates and returns the elements of S∩[0,n) in increasing order.
Line L1. Let aˉ=amodn and bˉ=bmodn. Since aˉ≡a and bˉ≡b(modn), we have ax−b≡aˉx−bˉ(modn) for every x, so the set S does not change. Also gcd(aˉ,n)=gcd(a,n). From here on, a and b denote the reduced values, with 0≤a,b<n.
Lemma 1 (line L2). The loop form of EXTENDED-EUCLID on (a,n) with a,n≥0, not both 0, terminates and returns (d,x′,y′) with d=gcd(a,n)≥1 and ax′+ny′=d.
Proof. The loop keeps the invariant r0=as0+nt0, r1=as1+nt1 and gcd(r0,r1)=gcd(a,n). It holds at the start, with (r0,r1)=(a,n), (s0,s1)=(1,0) and (t0,t1)=(0,1). One pass replaces (r0,r1) by (r1,r0−qr1) with q=⌊r0/r1⌋, and each coefficient pair by the same linear combination, so both identities hold after the pass; and gcd(r1,r0−qr1)=gcd(r0,r1). All remainders are non-negative. From the second pass on, r1 strictly decreases, since 0≤r0modr1<r1; so the loop stops, with r1=0. Then gcd(r0,0)=r0, so r0=gcd(a,n), and r0=as0+nt0. Since n≥1, d≥1. □
Lemma 2 (structure of S). Let d=gcd(a,n) and m=n/d.
- If d∤b, then S=∅.
- If d∣b, then x′(b/d)∈S, and for any x∗∈S, S={x:x≡x∗(modm)}.
Proof. (1) If x∈S, then ax−b=nk for an integer k, so b=ax−nk is a multiple of d, because d divides a and n.
(2) By Lemma 1, ax′=d−ny′. Multiplying by b/d gives a⋅x′(b/d)=b−ny′(b/d), so n∣a⋅x′(b/d)−b, and x′(b/d)∈S.
Let x∗∈S. For any integer x, x∈S if and only if n∣a(x−x∗), since ax−b=a(x−x∗)+(ax∗−b) and n∣ax∗−b. Write a=da1 and n=dm, with gcd(a1,m)=1. Then n∣a(x−x∗) if and only if m∣a1(x−x∗), and, as gcd(a1,m)=1, by Euclid's lemma in its general form, if and only if m∣x−x∗. □
Line L3. If d∤b, by Lemma 2(1) S∩[0,n)=∅, and the algorithm returns the empty list, which is correct. From here on, d∣b.
Line L5. x0=(x′(b/d))modm satisfies 0≤x0<m and x0≡x′(b/d)(modm). By Lemma 2(2), with x∗=x′(b/d), x0∈S and S={x0+jm:j∈Z}.
Lines L6 to L9. We claim the following loop invariant: at the start of the pass with index i, for 0≤i≤d, the list X holds the elements of S∩[0,im) in increasing order, and these are x0,x0+m,…,x0+(i−1)m.
Initialization. For i=0, X is empty and [0,0) is empty.
Maintenance. The elements of S in [im,(i+1)m) are the x0+jm with im≤x0+jm<(i+1)m. Since 0≤x0<m, this holds exactly for j=i. So S∩[0,(i+1)m) is S∩[0,im) with the one element x0+im added, and that element is larger than all earlier ones. Line L8 appends exactly this element.
Termination. The loop runs for i=0,…,d−1 and stops with i=d. Since dm=n, the invariant gives that X is S∩[0,n) in increasing order, with d elements. Line L9 returns it.
Every loop terminates: the gcd loop by Lemma 1, and the final loop after d passes. So the algorithm returns, in increasing order, exactly the residues x∈{0,…,n−1} with ax≡b(modn). ■