Recurrences and arithmetic · Definition

Euclidean algorithm

discrete mathematicsnumber theoryalgorithms

Before you start you need to know

It avoids factoring: a few divisions give the greatest common divisor, even for huge numbers.

Definition

The Euclidean algorithm computes the greatest common divisor of two integers \(a\) and \(b\) by dividing repeatedly, replacing each pair by the divisor and the remainder, until the remainder is 0.

\[\gcd(a,b)=\gcd(b,\,a\bmod b)\]

Factoring a large number is hard, but dividing is easy. The Euclidean algorithm uses the fact that \(\gcd(a,b)=\gcd(b,r)\) when \(a=qb+r\): the common divisors of \(a\) and \(b\) are exactly those of \(b\) and \(r\). Repeat until the remainder is 0; the last nonzero remainder is the answer. For \(a=252\) and \(b=105\): \(252=2\cdot105+42\), \(105=2\cdot42+21\), \(42=2\cdot21+0\), so \(\gcd(252,105)=21\).

It always terminates because the remainders are nonnegative integers that strictly decrease. It is also very fast: every two steps the remainder at least halves, so the number of divisions is proportional to the number of digits. The worst case is two consecutive Fibonacci numbers: \(\gcd(89,55)\) needs 9 divisions, all with quotient 1. If \(a<b\), the first step simply swaps the numbers.

Working backwards through the divisions gives the extended version: integers \(x,y\) with \(ax+by=\gcd(a,b)\), Bézout's identity. It solves Diophantine equations \(ax+by=c\) and computes inverses modulo \(m\), the basis of RSA cryptography. A common mistake is to stop at the remainder 0 instead of taking the previous one: the answer is the last nonzero remainder, that is, the last divisor.

Think about it

Compute \(\gcd(48,18)\) with the algorithm and write down the remainders.

\(48=2\cdot18+12\), \(18=1\cdot12+6\), \(12=2\cdot6+0\). The greatest common divisor is 6.

Why does subtracting \(qb\) from \(a\) not change the common divisors?

If \(d\mid a\) and \(d\mid b\), then \(d\mid a-qb\); conversely, if \(d\mid b\) and \(d\mid a-qb\), then \(d\mid (a-qb)+qb=a\).

Exercises 10

References

  • Kenneth H. Rosen, Discrete Mathematics and Its Applications, 8th edition, McGraw-Hill, 2019. §4.3
  • Susanna S. Epp, Discrete Mathematics with Applications, 5th edition, Cengage, 2019. §4.8
  • Ralph P. Grimaldi, Discrete and Combinatorial Mathematics: An Applied Introduction, 5th edition, Pearson, 2003. §4.4