Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Euclid’s Algorithm in Depth

The oldest algorithm: its invariant, Lamé’s bound and the extended GCD.

Euclid's algorithm is about 2,300 years old and still the simplest fast way to compute a greatest common divisor. Its worst case was found in 1844: consecutive Fibonacci numbers, which force about log⁡φ\log_\varphi of the input in divisions, and never more than five per decimal digit. This lesson proves that, extends the algorithm to solve ax+by=gcd⁡(a,b)ax + by = \gcd(a, b), and follows it to a frontier where nobody knows whether gcds can be computed fast in parallel.

What you’ll learn

  • Prove Euclid's algorithm correct, with its invariant stated in terms of common divisors.
  • Prove Lamé's theorem, that consecutive Fibonacci numbers are the worst case, and derive the bounds k≤1+log⁡φbk \le 1 + \log_\varphi b and five steps per decimal digit.
  • Compute Bézout coefficients with the extended algorithm, prove its invariant, and use them for modular inverses and linear Diophantine equations.
  • Compare the bit complexity of Euclid, binary GCD and half-GCD algorithms, and state what is open.

The remainder sequence

Euclid's algorithm computes the gcd of integers a,b≥0a, b \ge 0, not both zero, by repeating (a,b)←(b,a mod b)(a, b) \leftarrow (b, a \bmod b) until b=0b = 0. Written out, it produces the remainder sequence

r0=a,r1=b,ri+1=ri−1 mod ri,r_0 = a,\qquad r_1 = b,\qquad r_{i+1} = r_{i-1} \bmod r_i,

with quotients qi=⌊ri−1/ri⌋q_i = \lfloor r_{i-1}/r_i \rfloor, so that ri−1=qiri+ri+1r_{i-1} = q_i r_i + r_{i+1}, up to the first rk+1=0r_{k+1} = 0. The answer is rkr_k, and kk is the number of division steps. (If a<ba < b, the first step only swaps them, with q1=0q_1 = 0.)

The proof is the one from Correctness: Invariants & Proofs: ri+1=ri−1−qirir_{i+1} = r_{i-1} - q_i r_i is an integer combination of ri−1r_{i-1} and rir_i, and ri−1=qiri+ri+1r_{i-1} = q_i r_i + r_{i+1} is an integer combination of rir_i and ri+1r_{i+1}, so whatever divides one pair divides the other. The bound of bb steps is wildly pessimistic, and the next step shows by how much.

Think first Euclid's Elements describes the method with repeated subtraction, (a,b)→(a−b,b)(a, b) \to (a - b, b) while a≥ba \ge b. Why does it matter whether you subtract or divide?

One division performs a whole run of subtractions at once, and the quotient qiq_i counts them. Subtracting, gcd⁡(106,1)\gcd(10^6, 1) takes a million steps; dividing, it takes one. The subtractive version is still studied (Knuth and Yao analyzed its average behavior in 1975), and its idea returns in binary GCD, where subtraction is cheap and division is avoided.

Lamé’s theorem: Fibonacci is the worst case

DerivationProof, by induction on k
  1. k=1:b≥F2=1,a≥F3=2k = 1:\qquad b \ge F_2 = 1,\qquad a \ge F_3 = 2

    Base, k=1k = 1: b≥1=F2b \ge 1 = F_2, and a>ba > b gives a≥2=F3a \ge 2 = F_3.

  2. r  ≥  Fk,b  ≥  Fk+1r \;\ge\; F_k, \qquad b \;\ge\; F_{k+1}

    Step, k≥2k \ge 2. The first division maps (a,b)(a, b) to (b,r)(b, r) with r=a mod br = a \bmod b, where 0<r<b0 < r < b because the run continues. The run from (b,r)(b, r) takes k−1k - 1 steps, so the induction hypothesis gives

  3. a  ≥  b+r  ≥  Fk+1+Fk  =  Fk+2a \;\ge\; b + r \;\ge\; F_{k+1} + F_k \;=\; F_{k+2}

    And a=qb+ra = qb + r with q≥1q \ge 1, so

  4. (Fk+2,Fk+1)→(Fk+1,Fk)→⋯→(F3,F2)=(2,1)→(1,0)(F_{k+2}, F_{k+1}) \to (F_{k+1}, F_k) \to \dots \to (F_3, F_2) = (2, 1) \to (1, 0)

    Tightness. From (Fk+2,Fk+1)(F_{k+2}, F_{k+1}), each step uses Fj+1 mod Fj=Fj−1F_{j+1} \bmod F_j = F_{j-1} and walks down the Fibonacci numbers to (F3,F2)=(2,1)(F_3, F_2) = (2, 1), then (1,0)(1, 0): exactly kk steps. An exhaustive search confirms that for every k≤12k \le 12 the pair with the smallest aa that needs kk steps is (Fk+2,Fk+1)(F_{k+2}, F_{k+1}).

Two corollaries give the bounds people quote. Since Fj+1≥φj−1F_{j+1} \ge \varphi^{j-1} for the golden ratio φ=(1+5)/2\varphi = (1 + \sqrt5)/2, the inequality b≥Fk+1b \ge F_{k+1} gives

k  ≤  1+log⁡φb  ≈  1+2.078ln⁡b  ≈  1+4.785log⁡10b.k \;\le\; 1 + \log_\varphi b \;\approx\; 1 + 2.078\ln b \;\approx\; 1 + 4.785\log_{10} b.

And since Fj+5=8Fj+5Fj−1≥10FjF_{j+5} = 8F_j + 5F_{j-1} \ge 10F_j for j≥2j \ge 2, we get F5d+2≥10dF_{5d+2} \ge 10^d, so a smaller number bb with dd decimal digits forces k≤5dk \le 5d: at most five division steps per decimal digit, which is the form of Lamé's theorem usually stated.

Predict before you look

How many division steps does Euclid's algorithm make on (F30,F29)=(832040,514229)(F_{30}, F_{29}) = (832040, 514229)?

Show the answer

28

(Fk+2,Fk+1)(F_{k+2}, F_{k+1}) takes exactly kk steps, so k=28k = 28. By Lamé's theorem, no pair whose smaller number is below F29=514229F_{29} = 514229 needs that many.

Extended Euclid and Bézout’s identity

Run the remainder sequence with bookkeeping and you get more than the gcd. Next to each remainder rir_i, keep integers xi,yix_i, y_i with axi+byi=ria x_i + b y_i = r_i. They start as (1,0)(1, 0) for r0=ar_0 = a and (0,1)(0, 1) for r1=br_1 = b, and follow the same recurrence as the remainders. This is the extended Euclidean algorithm:

python
def ext_gcd(a, b):            # a, b >= 0, not both 0
    x0, y0, x1, y1 = 1, 0, 0, 1
    r0, r1 = a, b
    while r1 != 0:
        # invariant: a*x0 + b*y0 == r0 and a*x1 + b*y1 == r1
        q = r0 // r1
        r0, r1 = r1, r0 - q * r1
        x0, x1 = x1, x0 - q * x1
        y0, y1 = y1, y0 - q * y1
    return r0, x0, y0         # a*x0 + b*y0 == r0 == gcd(a, b)

ext_gcd(240, 46) returns (2,−9,47)(2, -9, 47): 240⋅(−9)+46⋅47=−2160+2162=2240 \cdot (-9) + 46 \cdot 47 = -2160 + 2162 = 2. When neither input divides the other, the coefficients stay small: ∣x∣≤b/(2g)|x| \le b/(2g) and ∣y∣≤a/(2g)|y| \le a/(2g), where gg is the gcd.

DerivationWhy the invariant holds
  1. a⋅1+b⋅0=r0,a⋅0+b⋅1=r1a \cdot 1 + b \cdot 0 = r_0, \qquad a \cdot 0 + b \cdot 1 = r_1

    Initialization.

  2. a (xi−1−qixi)+b (yi−1−qiyi)  =  ri−1−qiri  =  ri+1a\,(x_{i-1} - q_i x_i) + b\,(y_{i-1} - q_i y_i) \;=\; r_{i-1} - q_i r_i \;=\; r_{i+1}

    Maintenance. Subtract qiq_i times row ii from row i−1i - 1; a linear combination of true equations is true:

  3. axk+byk=gcd⁡(a,b)a x_k + b y_k = \gcd(a, b)

    Exit. When rk+1=0r_{k+1} = 0, row kk reads axk+byk=rk=gcd⁡(a,b)a x_k + b y_k = r_k = \gcd(a, b). Minimality: every combination ax+byax + by is a multiple of every common divisor, gcd⁡(a,b)\gcd(a, b) included, so no positive combination is smaller.

Two applications run all of modular arithmetic:

  • Modular inverses. If gcd⁡(a,m)=1\gcd(a, m) = 1, then ax+my=1ax + my = 1 gives ax≡1(modm)ax \equiv 1 \pmod m, so x mod mx \bmod m is the inverse of aa. For a=7a = 7 and m=26m = 26, ext_gcd(7, 26) returns (1,−11,3)(1, -11, 3), and −11≡15-11 \equiv 15: indeed 7⋅15=105=4⋅26+17 \cdot 15 = 105 = 4 \cdot 26 + 1. Python computes it directly as pow(7, -1, 26).
  • Linear Diophantine equations. ax+by=cax + by = c has integer solutions if and only if g=gcd⁡(a,b)g = \gcd(a, b) divides cc. Then ax0+by0=gax_0 + by_0 = g gives the solution (x0c/g, y0c/g)(x_0 c/g,\ y_0 c/g), and all solutions are (x0c/g+t b/g,  y0c/g−t a/g)\big(x_0 c/g + t\,b/g,\ \ y_0 c/g - t\,a/g\big) for integers tt.
Check your understanding

Which of these equations has integer solutions?

  1. 6x+10y=76x + 10y = 7
  2. 6x+10y=86x + 10y = 8
  3. 4x+6y=14x + 6y = 1
  4. 12x+18y=312x + 18y = 3
Show the answer

B. 6x+10y=86x + 10y = 8

gcd⁡(6,10)=2\gcd(6, 10) = 2 divides 8. ext_gcd(6, 10) gives 6⋅2+10⋅(−1)=26 \cdot 2 + 10 \cdot (-1) = 2, so (x,y)=(8,−4)(x, y) = (8, -4) is a solution, and so is every (8+5t, −4−3t)(8 + 5t,\ -4 - 3t).

Faster gcds, and an open question

For numbers that fit in a machine word, Euclid's algorithm with hardware division is hard to beat. For long numbers the right cost is the number of bit operations on inputs of ℓ\ell bits:

  • Euclid with schoolbook division costs O(ℓ2)O(\ell^2) in total, not O(ℓ3)O(\ell^3), because the lengths of the quotients add up to at most about ℓ\ell; the proof is in Models of Computation.
  • Binary GCD (Stein, 1967) avoids division altogether and uses only shifts, subtractions and parity tests. It also costs O(ℓ2)O(\ell^2).
  • Lehmer's method (1938) runs most steps on the leading digits only, in single-precision arithmetic, and applies them to the full numbers in batches: the same O(ℓ2)O(\ell^2) with a much smaller constant.
  • Half-GCD (Knuth, 1970; Schönhage, 1971) splits the remainder sequence recursively, the way fast multiplication splits products, and runs in O(M(ℓ)log⁡ℓ)O(M(\ell)\log\ell), where M(ℓ)M(\ell) is the cost of multiplying ℓ\ell-bit numbers. With M(ℓ)=O(ℓlog⁡ℓ)M(\ell) = O(\ell\log\ell) (Harvey & van der Hoeven, 2021) that is O(ℓlog⁡2ℓ)O(\ell\log^2\ell). Big-number libraries such as GMP switch to subquadratic gcd for very large inputs.
python
def binary_gcd(a, b):                   # a, b >= 0
    if a == 0 or b == 0:
        return a | b
    shift = ((a | b) & -(a | b)).bit_length() - 1   # common factors of 2
    a >>= (a & -a).bit_length() - 1                 # make a odd
    while b:
        b >>= (b & -b).bit_length() - 1             # make b odd
        if a > b:
            a, b = b, a
        b -= a                                      # odd - odd is even
    return a << shift

Stein's rules: gcd⁡(2a,2b)=2gcd⁡(a,b)\gcd(2a, 2b) = 2\gcd(a, b); gcd⁡(2a,b)=gcd⁡(a,b)\gcd(2a, b) = \gcd(a, b) for odd bb; and gcd⁡(a,b)=gcd⁡(a,b−a)\gcd(a, b) = \gcd(a, b - a) for odd a≤ba \le b, where b−ab - a is even. x & -x isolates the lowest set bit, so each shift strips every factor of 2 at once. Checked against math.gcd on 200,000 random pairs.

Key takeaways

  • Euclid's algorithm keeps the set of common divisors unchanged, gcd⁡(a,b)=gcd⁡(b,a mod b)\gcd(a, b) = \gcd(b, a \bmod b), and stops because the second number strictly decreases.
  • Lamé (1844): kk division steps on a>b>0a > b > 0 force b≥Fk+1b \ge F_{k+1} and a≥Fk+2a \ge F_{k+2}, so consecutive Fibonacci numbers are the worst case, k≤1+log⁡φbk \le 1 + \log_\varphi b, and there are at most five steps per decimal digit; on average there are about 0.843ln⁡n0.843\ln n.
  • The extended algorithm keeps axi+byi=ria x_i + b y_i = r_i and ends with Bézout coefficients, which give modular inverses and all solutions of ax+by=cax + by = c when gcd⁡(a,b)\gcd(a, b) divides cc.
  • On ℓ\ell-bit numbers, Euclid and binary GCD cost O(ℓ2)O(\ell^2) bit operations and half-GCD O(M(ℓ)log⁡ℓ)O(M(\ell)\log\ell); whether gcd is in NC is open.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Which pair a>b>0a > b > 0, with the smallest possible aa, makes Euclid's algorithm take 10 division steps?

  1. (1024,512)(1024, 512)
  2. (144,89)(144, 89)
  3. (89,55)(89, 55)
  4. (100,99)(100, 99)
Show the answer

B. (144,89)(144, 89)

By Lamé's theorem, kk steps need a≥Fk+2a \ge F_{k+2}, and (F12,F11)=(144,89)(F_{12}, F_{11}) = (144, 89) takes exactly 10 steps.

Question 2

Which invariant does the extended Euclidean algorithm maintain for each remainder rir_i?

  1. rir_i divides both aa and bb
  2. xi+yi=rix_i + y_i = r_i
  3. axi+byi=ria x_i + b y_i = r_i
  4. xix_i and yiy_i are both positive
Show the answer

C. axi+byi=ria x_i + b y_i = r_i

It holds for r0=ar_0 = a and r1=br_1 = b by the choice of starting rows, and each new row is the old row minus qiq_i times the current one, exactly as for the remainders. At the end it gives axk+byk=gcd⁡(a,b)a x_k + b y_k = \gcd(a, b).

Question 3

What is the inverse of 3 modulo 11?

  1. 4
  2. 3
  3. 8
  4. It does not exist
Show the answer

A. 4

3⋅4=12=11+1≡1(mod11)3 \cdot 4 = 12 = 11 + 1 \equiv 1 \pmod{11}. It exists because gcd⁡(3,11)=1\gcd(3, 11) = 1, and the extended algorithm finds 3⋅4+11⋅(−1)=13 \cdot 4 + 11 \cdot (-1) = 1.

Question 4

Euclid's algorithm on two ℓ\ell-bit numbers makes O(ℓ)O(\ell) divisions of O(ℓ)O(\ell)-bit numbers. Why is its bit complexity O(ℓ2)O(\ell^2) and not O(ℓ3)O(\ell^3)?

  1. Because each division costs O(1)O(1)
  2. Because the numbers halve at every step
  3. It is O(ℓ3)O(\ell^3)
  4. Because a division with a qq-bit quotient costs O((1+q) ℓ)O((1 + q)\,\ell), and the quotient lengths add up to at most about ℓ\ell
Show the answer

D. Because a division with a qq-bit quotient costs O((1+q) ℓ)O((1 + q)\,\ell), and the quotient lengths add up to at most about ℓ\ell

Long quotients are expensive but rare: the product of all quotients is at most aa, so their lengths total at most ℓ\ell, plus one per step. The whole run costs O(ℓ (k+ℓ))=O(ℓ2)O(\ell\,(k + \ell)) = O(\ell^2).

Further reading

  • D. E. Knuth, The Art of Computer Programming, Vol. 2: Seminumerical Algorithms, 3rd ed. (Addison-Wesley, 1997), §4.5.2–4.5.3.
  • G. Lamé, "Note sur la limite du nombre des divisions dans la recherche du plus grand commun diviseur entre deux nombres entiers," Comptes Rendus de l'Académie des Sciences 19 (1844).
  • J. Stein, "Computational problems associated with Racah algebra," Journal of Computational Physics 1(3) (1967).
  • N. Möller, "On Schönhage's algorithm and subquadratic integer GCD computation," Mathematics of Computation 77 (2008).