65. Euclid’s Algorithm

Theorem 64.1 is fine for finding the GCD or LCM of two numbers when you know their prime factorization. Unfortunately, the known algorithms for finding the prime factorization are slow for large numbers. There is another, more efficient method for finding the GCD of two numbers which does not require knowledge of the prime factorization. It is based on this theorem:

65.1 Theorem: Euclid’s Algorithm

For all nonnegative integers $m$ and $n$:

EA.1 $\operatorname{GCD}(m,0) = m$ and $\operatorname{GCD}(0,n) = n$.

EA.2 Let $r$ be the remainder when $m$ is divided by $n$. Then

$$\operatorname{GCD}(m,n) = \operatorname{GCD}(n,r)$$

Proof Both parts of Theorem 65.1 follow from Definition 6.1, page 10. EA.1 follows because every integer divides 0 (Theorem 5.1(2)), so that if $m \neq 0$, then largest integer dividing $m$ and 0 is the same as the largest integer dividing $m$, which of course is $m$.

To prove EA.2, suppose $d$ is an integer that divides both $m$ and $n$. Since $r = m-qn$, where $q = m \operatorname{div} n$, it follows from Theorem 5.4, page 8, that $d$ divides $r$. Thus $d$ divides both $n$ and $r$.

Now suppose $e$ divides both $n$ and $r$. Since $m = qn + r$, it follows that $e$ divides $m$. Thus $e$ divides both $m$ and $n$.

In the preceding two paragraphs, I have shown that $m$ and $n$ have the same common divisors as $n$ and $r$. It follows that $m$ and $n$ have the same greatest common divisor as $n$ and $r$, in other words $\operatorname{GCD}(m,n) = \operatorname{GCD}(n,r)$.

65.1.1 How to compute the GCD Theorem 65.1 provides a computational process for determining the GCD. This process is the Euclidean algorithm. The process always terminates because every time EA.2 is used, the integers involved are replaced by smaller ones (because of Definition 60.1(Q.2), page 83) until one of them becomes 0 and EA.1 applies.

65.1.2 Example

$$\operatorname{GCD}(164,48) = \operatorname{GCD}(48,20) = \operatorname{GCD}(20,8) = \operatorname{GCD}(8,4) = \operatorname{GCD}(4,0) = 4$$

65.2 Pascal program for Euclid’s algorithm

A fragment of a Pascal program implementing the Euclidean algorithm is given formally in Program 65.1.

{M>0, N>0, K=M, L=N}
while N <> 0 do
  begin
    rem := M mod N;
    M := N;
    N := rem;
  end;
{M=GCD(K,L)}

Program 65.1: Pascal Program for GCD

Pages 92–93 of the book (PDF).