St ep k Equation Quotient and remainder
0
1071 = q
0
462 + r
0
q
0
= 2 and r
0
= 147
1
462 = q
1
147 + r
1
q
1
= 3 and r
1
= 21
2
147 = q
2
21 + r
2
q
2
= 7 and r
2
= 0; algorithm ends
The Euclidean algorithm can be visualized in terms of the tiling analogy given above for the
greatest common divisor.
[17]
Assume that we wish to cover an a-by-b rectangle with square
tiles exactly, where a is the larger of the two numbers. We first attempt to tile the rectangle
using b-by-b square tiles; however, this leaves an r
0
-by-b residual rectangle untiled, where
r
0
< b. We then attempt to tile the residual rectangle with r
0
-by-r
0
square tiles. This leaves a
second residual rectangle r
1
-by-r
0
, which we attempt to tile using r
1
-by-r
1
square tiles, and so
on. The sequence ends when there is no residual rectangle, i.e., when the square tiles cover the
previous residual rectangle exactly. The length of the sides of the smallest square tile is the
GCD of the dimensions of the original rectangle. For example, the smallest square tile in the
adjacent figure is 21-by-21 (shown in red), and 21 is the GCD of 1071 and 462, the
dimensions of the original rectangle (shown in green).
At every step k, the Euclidean algorithm computes a quotient q
k
and remainder r
k
from two
numbers r
k−1
and r
k−2
r
k−2
= q
k
r
k−1
+ r
k
where the magnitude of r
k
is strictly less than that of r
k−1
. The theorem which underlies the
definition of the Euclidean division ensures that such a quotient and remainder always exist
and are unique.
[18]
In Euclid's original version of the algorithm, the quotient and remainder are found by repeated
subtraction; that is, r
k−1
is subtracted from r
k−2
repeatedly until the remainder r
k
is smaller
than r
k−1
. After that r
k
and r
k−1
are exchanged and the process is iterated. Euclidean division
reduces all the steps between two exchanges into a single step, which is thus more efficient.
Moreover, the quotients are not needed, thus one may replace Euclidean division by the
modulo operation, which gives only the remainder. Thus the iteration of the Euclidean algorithm becomes simply
r
k
= r
k−2
mod r
k−1
.
Implementations of the algorithm may be expressed in pseudocode. For example, the division-based version may be programmed
as
[19]
function gcd(a, b)
while b ≠ 0
t:= b;
Subtraction-based
animation of the Euclidean
algorithm. T he initial
rectangle has dimensions
a = 1071 and b = 4 62.
Squares of size 4 62×4 62
are placed within it leaving
a 4 62×147 rectangle. T his
rectangle is tiled with
14 7×14 7 squares until a
21×14 7 rectangle is left,
which in turn is tiled with
21×21 squares, leaving no
uncovered area. T he
smallest square size, 21,
is the GCD of 1071 and
4 62.
Visualization
Euclidean division
Implementations