Theorem. \mathsf {GCDI} is correct [00KB]
- September 3, 2026
\mathsf {GCDI}(a,b) = \gcd (a,b).
Proof.
- September 3, 2026
Suppose we initially call \mathsf {GCDI}(m,n). Then we claim the following loop invariant: each time right before doing the loop check again, \gcd (a,b) = \gcd (m,n). That is, the \gcd of the current values of a and b is always equal to the \gcd of the original arguments to \mathsf {GCDI}.
We prove this by induction on the number of loop executions.
- In the base case, before the loop has executed at all, a and b are equal to the original arguments to \mathsf {GCDI}, hence the invariant holds trivially.
- Otherwise, suppose the invariant held after n loop iterations; we must show it will still hold after one more loop iteration. But this follows from the theorem GCD reduction via mod.
Finally, after the loop ends, we will have either a = 0 or b = 0, and we can see that we will return wichever one is nonzero. This correctly returns the \gcd of a and b since \gcd (a,0) = a. But because of the loop invariant we know that \gcd (a,b) = \gcd (m,n), hence \mathsf {GCDI}(m,n) = \gcd (m,n).
It might seem like we are done, but actually we are not—we do not know that the loop will ever stop! All we have proved so far is that if it ever stops, it will deliver the correct value, but that is a big if. It's worth remarking that our proof of correctness for \mathsf {GCDR} neatly sidestepped this issue because it was by induction on the size of the arguments to \mathsf {GCDR}: the proof that the function returns the correct value, and the proof that the function always stops after a finite amount of time, were both wrapped up into a single argument. With \mathsf {GCDI}, we must argue these two things separately.
So, why does \mathsf {GCDI} always stop? Each time through the loop, either a gets smaller and b stays the same, or b gets smaller and a stays the same: if the loop starts out with a \leq b, then b gets smaller, since b \bmod a < a \leq b. Otherwise a gets smaller, since a \bmod b < b < a. Since neither ever gets bigger and one gets strictly smaller every loop iteration, one of them must eventually hit 0, which will stop the loop.
Technically, this argument that \mathsf {GCDI} always stops is a proof by well-founded induction on pairs \mathbb {N}^2 under the well-founded relation \{((a,b), (x,y)) \mid (a < x \land b = y) \lor (a = x \land b < y)\}.Remark. ★ Pedantic comment about well-founded induction, for those who like that sort of thing [00KC]