EXTENDED-EUCLID Algorithm
Goal: Given 2 integers a and b compute integers x and y such that gcd (a, b) = ax + by.
EXTENDED-EUCLID (a, b)
1. if b = 0
2. then return (a, 1, 0)
3. (d', x', y') ← EXTENDED-EUCLID (b, a mod b)
4. (d, x, y) ← (d', y', x'– y' )
5. return (d, x, y )
For a=99 and b =78 the following table illustrates the values of variables d, x, y at different levels of recursion for the algorithm EXTENDED-EUCLID(99, 78). We can easily verify that gcd(99, 78) = 3 = -11(99) + 14(78).
The correctness of the algorithm is established from the following inductive argument.
Basis: Let d denote gcd(a, b). When EUCLID terminates b = 0 and d = a ⇒ x = 1, y = 0. Thus the arguments returned by EXTENDED-EUCLID is correct.
Inductive Hypothesis: Assume the values d', x', y' returned by EXTENDED-EUCLID(b, a mod b) is correct.
Induction Step: We have to show EXTENDED-EUCLID(a, b) correctly computes d, x, y.
d'= x'b + y' (a mod b) = x'b + y' (a - b) = y'a + (x'-
y')b = d
⇒ x = y' and y = x'- y '.
Reference:
1. Introduction to Algorithms , Second Edition, T. H. Cormen, C. E. Leiserson, R. Rivest and C. Stein, Prentice Hall India .