After some experimentation and search, I came up with the following definition:
emcd' :: Integer -> Integer -> (Integer,Integer,Integer)
emcd' a 0 = (a, 1, 0)
emcd' a b =
let (g, t, s) = emcd' b r
in (g, s, t - (q * s))
where
(q, r) = divMod a b
- What's the meaning behind this expression
t - (q * s)
?
I've tried to evaluate it by hand; even though I arrived at the correct result (1, -4, 15)
, I can't see why that expression returns the value of t
.
There is a famous method for calculating s
and t
in as + bt = gcd(a, b)
. In the process of finding the gcd, I get several equations.
By reversing the steps in the Euclidean Algorithm, it is possible to find these integers a
and b
. Those resulting equations look like the expression t - (q * s)
; however, I can't figure out the exact process.
Since
(q, r) = divMod a b
, we have the equationand because of the recursive call, we have:
Substituting
a-qb
forr
in the second equation, that meansThis explains why
s
andt - q*s
are good choices to return.