The Extended Euclidean Algorithm
Suppose you want a single equation expressing as an integer combination of and . The ordinary Euclidean Algorithm tells you the gcd is . But it does not, by itself, hand you integers and with . Bezout's Identity guarantees such exist. However, existence proofs are often non-constructive in spirit, even when the underlying algorithm is finite. The Extended Euclidean Algorithm closes this gap. It runs the same division steps as the ordinary algorithm. Along the way, it records enough bookkeeping data. It then unwinds that data to produce explicit Bezout coefficients. This is not a cosmetic upgrade. The coefficients themselves are the object of interest in an enormous range of applications. Solving a Linear Congruence reduces to finding a Bezout pair for and . Computing a Modular Inverse of modulo is nothing more than this. It is the cornerstone of modular arithmetic, the RSA cryptosystem, and the Chinese Remainder Theorem. It amounts to reading off the coefficient of in a Bezout identity with . Without an explicit algorithm, one would be reduced to search or guesswork. With it, the computation is as mechanical as long division, and just as fast. The big picture is that number theory has two layers. There are existence statements: there is a gcd, there are Bezout coefficients. And there are constructive procedures that realize those statements as finite computations. The Euclidean Algorithm itself already exemplifies this for the gcd. The Extended Euclidean Algorithm does the same job one level up. It works for the linear combination witnessing that gcd. It is the bridge between the abstract identity and a concrete pair . That pair is one you can write down and verify. This article gives the precise algorithm. It proves the algorithm terminates and is correct. It works two genuinely asymmetric examples by hand. It shows exactly which hypothesis makes the whole machine run: finiteness of the division chain, and integrality of the remainders. It closes by connecting the coefficients directly to modular inverses and linear congruences, the natural next topics.
- The ordinary Euclidean Algorithm computes ; the extended version also computes integers with .
- It works by running the division algorithm forward, then substituting back through the chain of remainders from the last nontrivial step to the first.
- Equivalently, one can carry a pair of auxiliary sequences forward alongside the remainders, avoiding an explicit back-substitution pass.
- The algorithm terminates in division steps, the same bound as the ordinary Euclidean Algorithm.
- Bezout coefficients are never unique; the algorithm produces one particular solution, and all others differ by multiples of and .
- Its main downstream use is computing modular inverses: if , the produced satisfies .
- Key idea: run Euclid's division steps forward to reach the gcd, then substitute backward to express that gcd as an explicit integer combination of the original two numbers.
Where this lives today
The Extended Euclidean Algorithm is the standard method for computing multiplicative inverses modulo , which underlies the RSA cryptosystem's key generation (computing the private exponent as the inverse of the public exponent modulo ) and virtually all modular-arithmetic-based cryptography, including elliptic curve arithmetic over finite fields. In computer algebra systems, the polynomial analogue of the same algorithm computes greatest common divisors and partial-fraction-style decompositions of rational functions. In the Chinese Remainder Theorem, reconstructing a residue from several congruences requires exactly the Bezout coefficients this algorithm supplies. It is also the standard route to solving general linear congruences , and more generally linear Diophantine equations , whenever divides : scale the algorithm's Bezout pair by . In lattice-based algorithms and continued fraction theory, the coefficient sequences are exactly the numerators and denominators of the convergents of the continued fraction expansion of , linking this elementary algorithm to Diophantine approximation.
Ask the tutor: How do I use the Bezout coefficients from this algorithm to solve a general linear congruence ?
Let be integers, not both zero. A pair of integers is called a Bezout pair for if
The Extended Euclidean Algorithm is the following procedure. Assume (the general case reduces to this one, as discussed in the Scope table). Apply the division algorithm repeatedly:
where is the last nonzero remainder. Define auxiliary integer sequences by the recursions
Then and form a Bezout pair: . Equivalently and non-circularly, one may compute the same pair by back-substitution: starting from the equation , repeatedly replace each remainder using the division equation that produced it, working backward until only and remain.
Intuition
Picture the Euclidean Algorithm as a staircase descending from and down to , one remainder at a time. Each step of the staircase is a division equation, and each equation is a small, exact bookkeeping fact: it says one remainder is a specific integer combination of the two remainders just above it. The ordinary algorithm only cares about the value at each step, and eventually reports , the gcd. The extended algorithm insists on remembering the recipe — the exact combination of and that produced — at every rung. Once you reach the bottom rung, , you have a recipe expressing it in terms of . But itself has a recipe in terms of from the step above, so you substitute that in. This telescopes all the way up the staircase: at each substitution the expression is rewritten purely in terms of remainders one level higher, until only and remain, at which point you have for explicit integers . The forward recursion for in the definition is simply this same substitution process performed forward instead of backward — it computes, at each stage , the coefficients such that , so that no separate back-substitution pass is even needed.
The central theorem
Let be positive integers. Define the sequences as in the Definition above. Then: 1. (Termination) There is a finite index with and ; the algorithm halts after division steps. 2. (Invariant) For every with ,
3. (Correctness) In particular , so is a Bezout pair: .
Termination. This is the finiteness statement already established for the ordinary Euclidean Algorithm, restated for completeness since the extended algorithm shares its division chain. By the division algorithm, at each step for , so the sequence is a strictly decreasing sequence of nonnegative integers. A strictly decreasing sequence of nonnegative integers cannot be infinite, since it would otherwise produce an infinite strictly decreasing chain inside , a finite set. Hence the sequence reaches after finitely many steps; let be the index with and (such exists because , so at least one nonzero term occurs, and the terms eventually hit ). That is the content of the ordinary Euclidean Algorithm's correctness: each division equation shows , because any common divisor of divides , and any common divisor of divides ; hence the two pairs have exactly the same set of common divisors, and in particular the same gcd. Chaining these equalities,
using , which holds since every integer divides and the largest common divisor of and is itself.
Invariant, by strong induction on . Base cases : We have , and , matching the definitions of . Inductive step: Fix with , and suppose the invariant holds for indices and , i.e.
By the defining division equation at this stage of the algorithm,
Substitute the inductive hypotheses:
By the definitions and , this is exactly , completing the induction. Note this induction uses only the two immediately preceding cases at each stage, so it is a valid strong induction with no circularity: the recursion for (a fact already proved about the ordinary algorithm) is used only to justify the identity for the new index , never to reprove anything about smaller indices.
Correctness. Taking in the invariant (valid since ) gives . Combined with from the termination step, we obtain
so is a Bezout pair, as claimed.
∎The value produced by the forward recursion equals the pair obtained by starting from and repeatedly eliminating using the division equations, until only and remain.
Both procedures produce, at the point where all remainders have been eliminated, an expression of the form equal to . By the invariant proved above, is one such expression. It remains to see that back-substitution yields the same , not merely some pair satisfying the identity. This follows because at every stage of back-substitution the coefficients of and are uniquely determined: substituting into an expression already written in the remainders produces a unique new expression in by simple algebraic rearrangement (collecting coefficients of and ), with no choice involved at any stage. Since both the forward recursion and back-substitution implement exactly the same telescoping substitution — merely computed in opposite orders — and both terminate in the unique expression , the coefficients they produce coincide.
∎Worked examples
Example 1: , (asymmetric, several steps, negative intermediate coefficients). Run the Euclidean divisions:
So , , , , ; the gcd is , with , , , . Back-substitution. From the second equation, ... rather, isolate the remainder at each step:
From the first equation, . Substitute:
So
Check directly: , and ; indeed . ✓. Forward recursion, as a cross-check. ; .
Check: . ✓
Check: . ✓ — matching the back-substitution answer exactly, as the corollary guarantees.
Example 2: , (smaller numbers, , and used to extract a modular inverse afterward). Divisions ( — note the algorithm works regardless of which is larger, since the very first division step would just swap them; to avoid a wasted step, start directly with the larger one on top): Take instead (relabeling so ; a Bezout pair for converts trivially to one for by swapping coordinates):
So , , , . Back-substitution: directly, , so
Check: . ✓. Translating back to the original order : , i.e. the Bezout pair for is . Since , this does not directly give an inverse; but suppose instead we wanted the inverse of modulo (coprime to ). Then :
Here , gcd , , . Back-substitute starting from the last nontrivial remainder:
Replace :
Replace :
So , giving the Bezout pair for , i.e.
Check: , and . ✓ So ; indeed . ✓ This is exactly the Modular Inverse computation that the Extended Euclidean Algorithm exists to make routine.
The theorem as stated assumes . If one naively allows (still with ), the very first division step becomes , which is not a valid instance of the division algorithm — division by is undefined, so cannot be chosen at all, and the recursion for , hence the whole apparatus, never gets started. Concretely, take , . We know independently that , and a Bezout pair is visible by inspection: for any integer . But the algorithm's machinery cannot produce this: with , the required division with demands , which is impossible, since forces the remainder bound to be vacuous/contradictory. So the induction's base step for producing fails outright — there is no valid first division to anchor the invariant . This shows precisely why the algorithm is stated for (equivalently, handles the case as an explicit base case outside the main loop, returning immediately) rather than letting the general recursion run unchecked: the hypothesis " whenever a division step is invoked" is what makes each well-defined, and removing it produces a division by zero rather than a wrong-but-computable answer.
Scope, edge cases & common traps
| Situation | What to do |
|---|---|
| or negative | Run the algorithm on , get , then flip sign: if replace by (and similarly for ), since . |
| Base case: (assuming ), Bezout pair ; do not enter the division loop. | |
| is conventionally ; the identity holds for all , so Bezout pairs are not unique in the strongest possible sense — this case is usually excluded by hypothesis. | |
| Uniqueness of | Never unique when and are both nonzero: if works, so does for any integer , where . |
| Want smallest positive | Take the algorithm's output and reduce modulo , adjusting to compensate. |
The mathematician behind it
Origins · 1 minEuclid of Alexandria and how this was discovered
Euclid compiled and systematized geometry and number theory in the Elements, including the algorithm for the greatest common measure of two magnitudes (Book VII, Propositions 1–2), which is the ordinary Euclidean Algorithm in essentially its modern form. The extended version — with explicit integer coefficients rather than just the successive remainders — is not present in Euclid's text; it crystallizes only once Bezout's identity is formulated and one asks for its coefficients constructively. The name "Extended Euclidean Algorithm" is thus a later attribution, honoring the parent procedure while marking a genuinely later addition built directly on top of it.
Is the Bezout pair produced by the Extended Euclidean Algorithm unique?
No. If , then for any integer , the pair also satisfies the identity, since the extra terms cancel. This produces infinitely many valid Bezout pairs whenever are both nonzero. The algorithm returns one specific pair determined by the exact sequence of quotients encountered; a different but equally valid run (for instance starting the division chain from instead of ) can produce a different pair from this same infinite family. If a unique "canonical" pair is desired, one typically normalizes by requiring to lie in a fixed range, such as .
Why not just guess-and-check integer coefficients instead of running the algorithm?
Guessing works for tiny numbers but scales terribly: the search space for with has no natural finite bound to search over without already knowing a solution exists and roughly how large it is. The Extended Euclidean Algorithm instead guarantees termination in steps — the same bound as the plain Euclidean Algorithm — and produces the coefficients mechanically at each step, with no search at all. For numbers with hundreds of digits, as in cryptographic applications, guess-and-check is computationally infeasible, while the extended algorithm remains fast.
How does this connect to computing a modular inverse?
If , running the algorithm on yields integers with . Reducing modulo kills the term, leaving , so is precisely the multiplicative inverse of modulo . This is the standard, most efficient general method for computing modular inverses, and it is exactly what is used in place of, say, Euler's theorem (which would require computing , generally far more expensive).
Does the algorithm work if or is negative?
Yes, with a small adjustment. Run the algorithm on the absolute values to get a Bezout pair for , using . Then negate the corresponding coefficient: if , replace with ; if , replace with . The resulting pair satisfies because negating both the sign of the input and the sign of its coefficient leaves the product unchanged.
What is the relationship between the sequences and continued fractions?
The quotients produced during the Euclidean divisions are exactly the partial quotients of the continued fraction expansion of . The sequences (up to sign and an index shift) are precisely the numerators and denominators of the convergents of that continued fraction. This is why the Extended Euclidean Algorithm and continued fraction convergents give the same growth-rate and size bounds on the resulting Bezout coefficients, and it is the reason continued fractions provide an alternative computational route to the same coefficients.
Can the algorithm be adapted to polynomials instead of integers?
Yes. Given two polynomials over a field, the same division-with-remainder structure holds (using polynomial long division and comparing degrees instead of absolute values), so both the ordinary and extended Euclidean Algorithms carry over essentially verbatim, computing and polynomials with . This polynomial version is a standard tool in computer algebra, coding theory (decoding Reed–Solomon codes), and in constructing field extensions via minimal polynomials.
Is there a matrix formulation of the algorithm?
Yes. Each division step corresponds to multiplying the column vector by the matrix to get . Multiplying all these matrices together in order gives a single integer matrix with determinant that directly encodes the final Bezout coefficients as its entries. This viewpoint makes clear why the coefficients are always integers (the matrices are integer matrices with determinant , hence so is any product) and connects the algorithm to the group .