The extended Euclidean Algorithm

It is always possible to express the greatest common divisor of two nonzero natural numbers as a integer linear combination of such two numbers:

gcd (a, b) = m a + n b,

where m,n≠0 are integers. Working backwards in the above equations it is possible to express the last nonzero remainder in terms of previous ones, until we get an expression in terms of a and b. The corresponding algorithm is called the extended Euclidean algorithm. In the following implementation the algorithm takes a and b as input and outputs a list where the first element is gcd(a,b) and the next two are m and n, the coefficients of a and b.

GCD2[1547, 560]

{7, 21, -58}

GCD2[21, 34]

{1, 13, -8}

GCD2[18, 12]

{6, 1, -1}

GCD2[12, 18]

{6, -1, 1}

This algorithm is useful when solving linear Diophantine equations of the form ax+by=z where a,b,x,y,z∈Z, such as

172 x + 20 y = 1000.

First we note that the gcd of 172 and 20 divides 1000, so the equation is solvable.

GCD2[172, 20]

{4, 2, -17}

So from the extended Euclidean algorithm we have 2(172)-17(20)=4, and by multiplying this equation by 1000/4we get

172 (2 1000/4) - 20 (17 1000/4)

1000

So x_0=2(1000/4)= 500, and y_0=-17(1000/4)=-4250 are solutions to the equation. It is easily seen that if x_0and y_0are solutions to the equation, then so are

x = x_0 + b/dt, y = y_0 - a/dt,

where d is the gcd(a,b)and t is any integer.


Created by Mathematica  (June 3, 2006) Valid XHTML 1.1!