Sub topic 10
The Extended Euclidean Algorithm and Bézout's Identity
Euclid's algorithm tells you what the greatest common divisor is. The extended version also tells you how to build it from the original inputs. For any integers a and b, it finds integers x and y such that a*x + b*y = gcd(a, b). These coefficients answer questions the plain GCD cannot. They show whether a linear equation has integer solutions, and they give you modular inverses, which the next chapter covers.
This chapter assumes you know the invariant gcd(a, b) = gcd(b, a mod b), the iterative and recursive forms of Euclid's algorithm, and the termination argument from earlier chapters. You should also be comfortable with proofs by induction.
Bézout's Identity
Bézout's identity states: if a and b are integers, not both zero, then there exist integers x and y with
a*x + b*y = gcd(a, b).
The integers x and y are called Bézout coefficients. Some facts about them:
- They are not unique. If
(x, y)works, then so does(x + k*b/g, y - k*a/g)for every integerk, whereg = gcd(a, b). - Usually one coefficient is positive and the other is negative (or zero).
gcd(a, b)is the smallest positive value thata*x + b*ycan take. Every integer combination ofaandbis a multiple ofg, becausegdivides both terms.
That last fact has a useful consequence. The equation a*x + b*y = c has integer solutions exactly when g divides c.
The Core Idea: Track Every Remainder as a Combination
Euclid's algorithm produces a sequence of remainders:
r0 = ar1 = br(i+1) = r(i-1) - q(i) * r(i), whereq(i) = r(i-1) // r(i)
The sequence stops when a remainder hits zero. The last nonzero remainder is the GCD.
The key observation is that every remainder is an integer combination of a and b. The first two are trivial:
r0 = a = a*1 + b*0r1 = b = a*0 + b*1
Each new remainder is the previous one minus a multiple of the current one. So if two consecutive remainders are combinations of a and b, the next one is too. Write r(i) = a*s(i) + b*t(i). Then:
r(i+1) = r(i-1) - q(i)*r(i) = a*(s(i-1) - q(i)*s(i)) + b*(t(i-1) - q(i)*t(i))
So the coefficients follow the same recurrence as the remainders:
s(i+1) = s(i-1) - q(i) * s(i)t(i+1) = t(i-1) - q(i) * t(i)
This gives a proof of Bézout's identity by induction. The invariant r(i) = a*s(i) + b*t(i) holds for i = 0 and i = 1. It is preserved by each step. The algorithm terminates. So the invariant holds for the last nonzero remainder, which is gcd(a, b).
Tracing an Example by Hand
Take a = 240 and b = 46. Each row records a remainder and its coefficients. You can check any row by confirming 240*s + 46*t = r.
| i | r | q | s | t | Check: 240s + 46t |
|---|---|---|---|---|---|
| 0 | 240 | 1 | 0 | 240 | |
| 1 | 46 | 5 | 0 | 1 | 46 |
| 2 | 10 | 4 | 1 | -5 | 240 - 230 = 10 |
| 3 | 6 | 1 | -4 | 21 | -960 + 966 = 6 |
| 4 | 4 | 1 | 5 | -26 | 1200 - 1196 = 4 |
| 5 | 2 | 2 | -9 | 47 | -2160 + 2162 = 2 |
| 6 | 0 | 23 | -120 | 5520 - 5520 = 0 |
In row i, the quotient q is r(i-1) // r(i), and it is used to compute row i+1. The last nonzero remainder is 2 in row 5, so gcd(240, 46) = 2 with x = -9 and y = 47.
The zero row is worth a look. Its coefficients are 23 = 46/2 and -120 = -240/2, which is (b/g, -a/g) up to sign. Adding multiples of that row to row 5 gives every other Bézout pair. That is where the general solution (x + k*b/g, y - k*a/g) comes from.
Iterative Implementation
The iterative form keeps only two consecutive rows of the table at a time:
def extended_gcd(a, b):
# Returns (g, x, y) with a*x + b*y == g == gcd(a, b), for a, b >= 0
old_r, r = a, b
old_s, s = 1, 0
old_t, t = 0, 1
while r != 0:
q = old_r // r
old_r, r = r, old_r - q * r
old_s, s = s, old_s - q * s
old_t, t = t, old_t - q * t
return old_r, old_s, old_t
print(extended_gcd(240, 46)) # (2, -9, 47)Python's tuple assignment evaluates the whole right-hand side before assigning, so old_r - q * r uses the old value of r. In a language without simultaneous assignment, you need a temporary variable for each pair. Forgetting it is the most common bug in ports of this function.
Recursive Implementation
The recursive form works backwards. Suppose the recursive call on (b, a mod b) returns g, x1, y1 with b*x1 + (a mod b)*y1 = g. Substitute a mod b = a - (a // b)*b:
b*x1 + (a - (a//b)*b)*y1 = a*y1 + b*(x1 - (a//b)*y1) = g
So the coefficients for (a, b) are y1 and x1 - (a//b)*y1. The base case is gcd(a, 0) = a = a*1 + 0*0.
def extended_gcd_recursive(a, b):
# Returns (g, x, y) with a*x + b*y == g, for a, b >= 0
if b == 0:
return a, 1, 0
g, x1, y1 = extended_gcd_recursive(b, a % b)
return g, y1, x1 - (a // b) * y1
print(extended_gcd_recursive(240, 46)) # (2, -9, 47)On (240, 46) both versions return the same coefficients. The recursion depth equals the number of division steps, which Lamé's theorem keeps small. A pair of 1000-digit numbers needs only a few thousand levels. That is still above Python's default recursion limit of 1000, so prefer the iterative form for large inputs.
Handling Zero and Negative Inputs
Both functions above assume a, b >= 0. The zero cases already work:
extended_gcd(a, 0)returns(a, 1, 0).extended_gcd(0, b)runs one iteration and returns(b, 0, 1).extended_gcd(0, 0)returns(0, 1, 0). The identity0*1 + 0*0 = 0holds, thoughgcd(0, 0) = 0is a convention.
For negative inputs, compute on absolute values and then flip the sign of each coefficient whose input was negative. If |a|*x + |b|*y = g and a < 0, then a*(-x) = |a|*x.
def extended_gcd_signed(a, b):
g, x, y = extended_gcd(abs(a), abs(b))
if a < 0:
x = -x
if b < 0:
y = -y
return g, x, y
g, x, y = extended_gcd_signed(-240, 46)
print(g, x, y, -240 * x + 46 * y) # 2 9 47 2How Large Do the Coefficients Get?
Coefficient growth matters for fixed-width integer types. For a, b > 0 where neither divides the other, the coefficients the algorithm returns satisfy:
|x| <= b / (2g)|y| <= a / (2g)
In the example, |-9| <= 46/4 = 11.5 and 47 <= 240/4 = 60. So the coefficients never get larger than the inputs, and if a and b fit in a signed 64-bit integer, so do x and y. The intermediate products q * s stay bounded as well. The final zero row, with values b/g and a/g, is the largest one, and you can skip computing it if overflow is tight.
Tracking Only One Coefficient
Often you need only one coefficient. Computing a modular inverse needs only x, for example. Since a*x + b*y = g, you can drop the t sequence and recover y at the end with one exact division:
def extended_gcd_half(a, b):
# Tracks only s; computes t from a*s + b*t == g. Requires a, b >= 0, b != 0.
old_r, r = a, b
old_s, s = 1, 0
while r != 0:
q = old_r // r
old_r, r = r, old_r - q * r
old_s, s = s, old_s - q * s
g = old_r
y = (g - a * old_s) // b
return g, old_s, y
print(extended_gcd_half(240, 46)) # (2, -9, 47)The division (g - a*x) // b is exact because g - a*x = b*y. This saves about a third of the arithmetic in the loop.
Application: Solving Linear Diophantine Equations
A linear Diophantine equation is an equation a*x + b*y = c where you want integer solutions. Bézout's identity settles it completely:
- Compute
g, x0, y0 = extended_gcd(a, b). - If
c % g != 0, there is no integer solution. - Otherwise, one solution is
x = x0 * (c // g),y = y0 * (c // g). - All solutions are
x + k*(b // g),y - k*(a // g)for integerk.
def solve_diophantine(a, b, c):
# Returns one solution (x, y) of a*x + b*y == c, or None. Requires a, b >= 0, not both 0.
g, x0, y0 = extended_gcd(a, b)
if c % g != 0:
return None
k = c // g
return x0 * k, y0 * k
print(solve_diophantine(240, 46, 6)) # (-27, 141)
print(solve_diophantine(6, 10, 7)) # NoneYou can check the first result: 240*(-27) + 46*141 = -6480 + 6486 = 6.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Sequential instead of simultaneous updates | Coefficients fail the identity | Use tuple assignment or temporaries |
| Returning `s, t` instead of `old_s, old_t` | Returns the zero-row coefficients `(b/g, -a/g)` | Return the values paired with `old_r` |
| Wrong initial values | Identity fails from the first row | Start with `(1, 0)` for `s` and `(0, 1)` for `t` |
| Passing negative inputs unnormalized | Negative gcd or broken identity | Use absolute values, then fix signs |
| Expecting specific coefficients | Tests fail on valid answers | Test `a*x + b*y == g` instead |
Exercise
Trace the extended Euclidean algorithm on a = 99, b = 78. Give gcd(99, 78) and the coefficients x and y that the iterative implementation returns, and verify them.
Show answer
The remainders are 99, 78, 21, 15, 6, 3, 0 with quotients 1, 3, 1, 2, 2. The (s, t) pairs are (1, 0), (0, 1), (1, -1), (-3, 4), (4, -5), (-11, 14). So gcd = 3 with x = -11, y = 14. Check: 99 (-11) + 78 14 = -1089 + 1092 = 3.
Exercise
Does 6x + 10y = 7 have an integer solution? What about 6x + 10y = 8? If so, give one solution.
Show answer
gcd(6, 10) = 2. Since 2 does not divide 7, the first equation has no integer solutions. For 8, extended_gcd(6, 10) gives 62 + 10(-1) = 2. Multiplying by 4 gives x = 8, y = -4, and 68 + 10(-4) = 8.
Exercise
Given one Bézout pair (-9, 47) for a = 240, b = 46, find the pair with the smallest positive x.
Show answer
With g = 2, all solutions are x = -9 + 23k and y = 47 - 120k. Taking k = 1 gives x = 14, y = -73. Check: 24014 + 46(-73) = 3360 - 3358 = 2.
Exercise
In the recursive version, why must the base case return (a, 1, 0) rather than (a, 0, 1)?
Show answer
When b = 0, the identity requires ax + 0y = a, so x must be 1. The value of y is arbitrary, and 0 is the conventional choice. Returning (a, 0, 1) would claim a0 + 01 = a, which is false unless a = 0.