Algorithm. Extended Euclid’s Algorithm [01EU]

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)))