Skip to content
Go back

Euclid's Algorithm (Algorithm E, §1.1)

Published:  at  09:00 AM

Euclid's Algorithm

Algorithm E
TAOCP Vol. 1 | §1.1

Given two positive integers mm and nn, find their greatest common divisor (GCD) — the largest positive integer that divides both mm and nn without remainder.

Table of contents

Open Table of contents

Visual Intuition

The idea behind Euclid’s algorithm is simple: if you want the GCD of two numbers, you can repeatedly replace the larger number with the remainder of dividing it by the smaller, until the remainder is zero. The last non-zero remainder is the GCD.

Here is Algorithm E applied to m=119m = 119 and n=544n = 544:

E1: Divide544 = 4 × 119 + 68r = 68 ≠ 0E1: Divide119 = 1 × 68 + 51r = 51 ≠ 0E1: Divide68 = 1 × 51 + 17r = 17 ≠ 0E1: Divide51 = 3 × 17 + 0r = 0 → done!GCD = 17E1: Dividem ÷ n → rE2r = 0?yesn = GCDnoE3: Reducem ← n, n ← r

The left side shows the computation trace for gcd(544,119)\gcd(544, 119). The right side shows the algorithm’s flow: divide, check if the remainder is zero, and loop until it is.

Knuth’s Formulation

Knuth defines Algorithm E with three steps:

E1. [Find remainder.] Divide mm by nn and let rr be the remainder. (We will have 0r<n0 \leq r < n.)

E2. [Is it zero?] If r=0r = 0, the algorithm terminates; nn is the answer.

E3. [Reduce.] Set mnm \leftarrow n, nrn \leftarrow r, and go back to step E1.

In mathematical notation, this computes:

gcd(m,n)=gcd(n,mmodn)\gcd(m, n) = \gcd(n, m \bmod n)

by repeatedly applying the identity until the second argument reaches zero.

The correctness relies on a key property: if m=qn+rm = qn + r, then any common divisor of mm and nn is also a divisor of rr, and vice versa. So gcd(m,n)=gcd(n,r)\gcd(m, n) = \gcd(n, r).

Relation to algorithm definition

Knuth maps Euclid’s algorithm onto this framework explicitly. For gcd(m,n)\gcd(m, n):

Complexity and Notes

Time complexity: O(log(min(m,n)))O(\log(\min(m, n))) — Gabriel Lame proved in 1844 that the number of steps is at most five times the number of digits in the smaller number. This was one of the first analyses of an algorithm’s running time.


Share this post on:

Previous Post
What is an Algorithm? Knuth's Computational Method
Next Post
Lower Body (PPL W7D6)