Extending Euclid’s algorithm [01ET]
- October 28, 2026
- Marcelo Fiore, Jon Sterling
We shall now extend Euclid’s algorithm \gcd {\mathopen {}\left (m,n\right )\mathclose {}} from computing on pairs of positive integers to computing on pairs of triples of integers ((s,t),r) with r positive, satisfying the invariant that s and t are coefficients representing r as a linear combination of m and n.
Algorithm Extended Euclid’s Algorithm [01EU]
- October 28, 2026
- Marcelo Fiore, Jon Sterling
We define a function
egcd : int * int -> (int * int) * int
such that egcd (m,n) computes a triple ((s,t), r) such that r is the greatest common divisor of m and n, and s and t are linear coefficients representing r as an integer linear combination of m and n.
In other words, the specification of egcd is that the value of egcd (m,n) is the triple {\mathopen {}\left ({\mathopen {}\left (\operatorname {lc}_1{\mathopen {}\left (m,n\right )\mathclose {}},\operatorname {lc}_2{\mathopen {}\left (m,n\right )\mathclose {}}\right )\mathclose {}}, \gcd {\mathopen {}\left (m,n\right )\mathclose {}}\right )\mathclose {}}. Here is the algorithm:
let rec iterate_egcd ((s1,t1),r1) ((s2,t2),r2) = let (q, r) = divide r1 r2 in if r = 0 then ((s2,t2),r2) else iterate_egcd ((s2,t2),r2) ((s1 - q * s2, t1 - q*t2), r) let egcd (m, n) = iterate_egcd ((1,0),m) ((0,1),n)
We used the division algorithm above. We may derive the ordinary gcd from the above, as well as the calculations of the coefficients representing the gcd as a linear combination of m and n:
let gcd_from_egcd (m, n) = snd (egcd (m, n)) let lc1 (m, n) = fst (fst (egcd (m, n))) let lc2 (m, n) = snd (fst (egcd (m, n)))
Example A trace of the extended Euclid’s algorithm [01EV]
- October 28, 2026
- Marcelo Fiore, Jon Sterling
egcd (13,34) |
iterate_egcd ((1,0),13) ((0,1),34)
|
iterate_egcd ((0,1),34) ((1,0),13)
|
iterate_egcd ((1,0),13) ((-2,1),8)
|
iterate_egcd ((-2,1),8) ((3,-1), 5)
|
iterate_egcd ((3,-1),5) ((-5,2),3)
|
iterate_egcd ((-5,2),3) ((8,-3),2)
|
iterate_egcd ((8,-3),2) ((-13,5),1)
|
((-13,5),1)
|
Proposition Flipping the linear coefficients of the greatest common divisors [01EX]
- October 28, 2026
- Marcelo Fiore, Jon Sterling
For all distinct positive integers m and n, \operatorname {lc}_1{\mathopen {}\left (m,n\right )\mathclose {}} = \operatorname {lc}_2{\mathopen {}\left (n,m\right )\mathclose {}}.