Garner's algorithm returns the unique solution in [0, M) full
This proof shows: correctness.
Notation. Let m1,…,mt≥1, let P0=1 and Pi=m1m2⋯mi, and let M=Pt. The residues are v1,…,vt.
Claim. The setup (lines L1 to L4) succeeds if and only if the moduli are pairwise coprime, and then Ci≡Pi−1−1(modmi) for 2≤i≤t. With these constants, lines L5 to L10 compute digits 0≤ui<mi, and lines L11 to L13 return
x=u1+u2P1+u3P2+⋯+utPt−1, which is the unique integer with 0≤x<M and x≡vi(modmi) for all i.
Setup. For each i≥2, line L2 computes p≡Pi−1(modmi), as a product of the factors mjmodmi reduced after each step. Line L3 computes g=gcd(p,mi)=gcd(Pi−1,mi) and, when g=1, Ci with CiPi−1≡1(modmi). A prime divides gcd(Pi−1,mi) exactly when it divides mi and some mj with j<i. So all the checks of line L4 pass if and only if every pair mj,mi with j<i is coprime.
Partial values. Let xi=u1+u2P1+⋯+uiPi−1. We prove by induction on i that 0≤xi<Pi and xi≡vj(modmj) for all j≤i.
- Base. Line L5 sets u1=v1modm1, so x1=u1∈[0,m1) and x1≡v1(modm1).
- The Horner loop. Fix i≥2. Define yi−1=ui−1 and yj=uj+mjyj+1 for j=i−2,…,1. Expanding, yj=∑l=ji−1ulmjmj+1⋯ml−1, so y1=xi−1. Line L7 sets s≡yi−1, and each pass of line L9, for j from i−2 down to 1, turns s≡yj+1 into s≡mjyj+1+uj=yj(modmi). After the loop, s≡xi−1(modmi).
- Step. Line L10 sets ui=(vi−s)Cimodmi, so 0≤ui<mi. Then
xi=xi−1+uiPi−1≡s+(vi−s)CiPi−1≡s+(vi−s)=vi(modmi). For j<i, mj∣Pi−1, so xi≡xi−1≡vj(modmj) by the induction hypothesis. For the range, 0≤xi≤(Pi−1−1)+(mi−1)Pi−1=Pi−1.
Evaluation. Lines L11 and L12 compute ut, then utmt−1+ut−1, and so on down to index 1. This is the Horner form of xt, so line L13 returns x=xt. By the induction, 0≤x<M and x≡vi(modmi) for all i.
Uniqueness. If x and x′ both satisfy all congruences, then every mi divides x−x′. The moduli are pairwise coprime, so their product M divides x−x′. Two different integers in [0,M) differ by less than M, so x=x′.
Empty system. For t=0, M=1 and the only value in [0,1) is 0, which the implementation returns. ■