The Extended Euclidean Algorithm

Finds integers x and y with ax + by = the greatest common divisor. Running the Euclidean algorithm while also tracking how many of a and of b each remainder holds leaves x and y behind once the division comes out even. This is the basis for solving linear Diophantine equations.

For two whole numbers aa and bb, this finds whole numbers xx and yy satisfying the following.

ax+by=gcd(a,b)ax + by = \gcd(a, b)

That such xx and yy always exist is known as Bezout's identity. The ordinary Euclidean algorithm returns only the greatest common divisor, but tracking how many of aa and of bb each remainder holds leaves xx and yy behind once the division comes out even.

Example

Take a=240a = 240 and b=46b = 46. The greatest common divisor is 2, with x=9x = -9 and y=47y = 47. Checking, 240×(9)+46×47=2160+2162=2240 \times (-9) + 46 \times 47 = -2160 + 2162 = 2.

Where it is used

A linear Diophantine equation ax+by=cax + by = c has whole-number solutions only when cc is a multiple of the greatest common divisor. This calculation finds one such solution to start from.

It also finds xx with ax1(modm)ax \equiv 1 \pmod{m}, the inverse modulo mm. When aa and mm share no factor, ax+my=1ax + my = 1 can be solved and that xx is the answer. Cryptography relies on this.

Notes

The pair xx, yy is not unique. Adding bgcd(a,b)\dfrac{b}{\gcd(a, b)} to xx and subtracting agcd(a,b)\dfrac{a}{\gcd(a, b)} from yy keeps the identity true. The pair the algorithm returns is the one given here.