The Extended Euclidean Algorithm
The extended Euclidean Algorithm [Rosen, Section 3.6 and Exercise 3.7.48] can be written as follows.
Let a and b be two positive integers. The Extended Euclidean Algorithm finds the greatest common divisor of a and b, gcd(a,b), and also expresses a and b as a linear combination with integer coefficients of the greatest common divisor, i.e., the algorithm finds gcd(a,b), and two integers s and t, such that
s * a + t * b =
gcd(a,b).
First write the following table:
| i | ri | qi | si | ti |
|---|---|---|---|---|
| 0 | a | - | 1 | 0 |
| 1 | b | 0 | 1 | |
| 2 | ||||
| ... | ||||
| n-1 | ||||
| n | gcd(a,b) | s | t | |
| n+1 | 0 |
Next, fill out the table by using the following four rules:
- ri = ri-2 mod ri-1.
- qi = ri-1 div ri. This is integer division, e.g., 7 div 3 = 2.
- si = si-2 - qi-1 si-1.
- ti = ti-2 - qi-1 ti-1.
You continue to use the rules until you reach an rn+1 with value zero. Then, the gcd of a and b is rn, i.e.,
gcd(a,b) =
sn * a + tn * b =
rn.
An example of this is the following:
| i | ri | qi | si | ti |
| 0 | 10001 | - | 1 | 0 |
| 1 | 13422 | 0 | 0 | 1 |
| 2 | 10001 | 1 | 1 | 0 |
| 3 | 3421 | 2 | -1 | 1 |
| 4 | 3159 | 1 | 3 | -2 |
| 5 | 262 | 12 | -4 | 3 |
| 6 | 15 | 17 | 51 | -38 |
| 7 | 7 | 2 | -871 | 649 |
| 8 | 1 | 7 | 1793 | -1336 |
| 9 | 0 | - |
That is:
gcd(a,b) =
gcd(10001, 13422) =
1793 * 10001 - 1336 * 13422 =
1