Sub topic 1
Divisors, Common Divisors, and the GCD
Euclid's algorithm computes one specific number: the greatest common divisor of two integers. Before you can trust the algorithm, you need an exact definition of what it computes. This chapter builds that definition from divisibility. It also covers the conventions for zero and negative numbers, the properties later chapters use, and two slow but correct ways to compute the GCD. Those slow methods give you a baseline to compare Euclid's algorithm against.
Prerequisites
This chapter assumes you are comfortable with:
- Basic integer arithmetic, including negative numbers.
- The remainder operator
%in Python, and the fact thata % d == 0tests whetherddividesaevenly. - Reading short Python functions with loops, sets, and dictionaries.
- Following short algebraic arguments of the form "assume X, then Y follows".
Proofs by induction come in later chapters. This one does not need them.
Divisibility
An integer d divides an integer n if there is an integer k with n = d * k. We write this as d | n, read "d divides n". Equivalent phrasings are "d is a divisor of n", "d is a factor of n", and "n is a multiple of d".
The definition asks for an integer k to exist. It says nothing about computing n / d with fractions. That has a few consequences that surprise people:
3 | 12because12 = 3 * 4.-3 | 12because12 = (-3) * (-4). Divisors can be negative.5 | 0because0 = 5 * 0. Every integer divides 0.0 | 0because0 = 0 * 7(or0 * kfor anyk). Zero divides itself.0 | 5is false, because no integerksatisfies5 = 0 * k.
So "d divides n" and "n / d is an integer" mean the same thing only when d is nonzero. Keep the multiplicative definition in mind. It is the one that handles zero correctly.
Properties you will use repeatedly
For all integers a, b, c, d, x, y:
- Reflexivity:
a | a. - Transitivity: if
a | bandb | c, thena | c. (Ifb = a*kandc = b*m, thenc = a*(k*m).) - Sign does not matter:
d | nexactly when|d|divides|n|. - Size bound: if
d | nandn != 0, then|d| <= |n|. (Fromn = d*kwithk != 0, we get|k| >= 1, so|n| = |d|*|k| >= |d|.) - Linear combinations: if
d | aandd | b, thend | (a*x + b*y)for any integersxandy.
Property 5 matters most for this tutorial. The proof takes one line. Write a = d*k and b = d*m. Then a*x + b*y = d*(k*x + m*y), and k*x + m*y is an integer. Two special cases are worth naming. With x = 1, y = -1, any common divisor of a and b also divides a - b. With x = 1, y = -q, it divides a - q*b. That second expression is the remainder from division, and it is the key step in the chapter on why gcd(a, b) = gcd(b, a mod b).
Common divisors
A common divisor of a and b is an integer that divides both. Take 12 and 18:
| Number | Positive divisors |
|---|---|
| 12 | 1, 2, 3, 4, 6, 12 |
| 18 | 1, 2, 3, 6, 9, 18 |
| Both (common) | 1, 2, 3, 6 |
The negatives -1, -2, -3, -6 are also common divisors. They always mirror the positive ones, so we usually list only the positive ones.
Look at how the common divisors relate to one another. Each of 1, 2, 3 divides 6. The largest common divisor is also a multiple of every other common divisor. The extended Euclidean algorithm chapter will show this holds for every pair of integers, so it is no accident of 12 and 18.
An arrow from x to y means x | y with nothing in between. The common divisors are the nodes from which you can reach both 12 and 18. Among them, 6 is the highest, and every other common divisor reaches 6.
The greatest common divisor
Assume a and b are not both zero. Then at least one of them, say a, is nonzero, and by property 4 every common divisor has absolute value at most |a|. Since 1 is always a common divisor, the set of common divisors is finite and nonempty. It therefore has a largest element. That element is the greatest common divisor, written gcd(a, b). It is always a positive integer.
For the leftover case, define gcd(0, 0) = 0. This is a convention, but a principled one. A more general definition says the GCD is the nonnegative common divisor that every other common divisor divides. Under that definition:
- For 12 and 18 it gives 6, the same answer as "largest".
- For 0 and 0, every integer is a common divisor, and the only nonnegative integer that every integer divides is 0. So
gcd(0, 0) = 0.
Python's math.gcd(0, 0) returns 0, and so do most libraries. With this convention, identities such as gcd(a, 0) = |a| hold for every a, including a = 0.
Two integers are coprime (or relatively prime) when gcd(a, b) = 1. In that case their only positive common divisor is 1. For example, 8 and 15 are coprime even though neither is prime. Coprimality decides when modular inverses exist, which a later chapter covers.
Basic GCD facts
These follow directly from the definitions above:
| Fact | Reason | Column |
|---|---|---|
| `gcd(a, b) = gcd(b, a)` | "Divides both" does not depend on order. | |
| `gcd(a, b) = gcd(abs(a), abs(b))` | Divisibility ignores sign (property 3). | |
| `gcd(a, 0) = abs(a)` | Every integer divides 0, so the common divisors of `a` and 0 are just the divisors of `a`. | |
| `gcd(a, a) = abs(a)` | Same reasoning as the row above. | |
| `gcd(a, 1) = 1` | 1 has no positive divisors other than 1. | |
| If `b \ | a` and `b != 0`, then `gcd(a, b) = abs(b)` | Every divisor of `b` also divides `a` (transitivity). |
The third row is the base case of Euclid's algorithm. When the second argument reaches 0, the answer is the absolute value of the first.
Computing the GCD from the definition
The definition already suggests an algorithm. Try candidates from the largest possible value downward and return the first one that divides both numbers.
def gcd_brute(a, b):
a, b = abs(a), abs(b)
if a == 0:
return b # gcd(0, b) = |b|, which also covers gcd(0, 0) = 0
if b == 0:
return a
for d in range(min(a, b), 0, -1):
if a % d == 0 and b % d == 0:
return d
print(gcd_brute(12, 18)) # 6
print(gcd_brute(-12, 18)) # 6
print(gcd_brute(0, 7)) # 7
print(gcd_brute(0, 0)) # 0
print(gcd_brute(1071, 462)) # 21The function is correct, and the zero cases come first on purpose. If you dropped them, min(a, b) would be 0 when one input is zero, the loop would never run, and the function would return None. The loop always ends at d = 1 at the latest, because 1 divides everything.
The cost is the problem. For 1071 and 462 the loop tests every candidate from 462 down to 21, which is 442 iterations. For coprime inputs it tests all min(a, b) candidates. If the inputs have 20 digits, that can mean around 10^20 iterations, which will not finish. Euclid's algorithm handles the same inputs in about a hundred steps or fewer.
Using prime factorizations
The method usually taught in school factors both numbers into primes. The GCD is the product of the shared primes, each raised to the smaller of its two exponents.
1071 = 3^2 * 7 * 17462 = 2 * 3 * 7 * 11- Shared primes: 3 (exponents 2 and 1, take 1) and 7 (exponents 1 and 1, take 1).
gcd = 3 * 7 = 21
def factorize(n):
"""Return {prime: exponent} for n >= 2, by trial division."""
factors = {}
p = 2
while p * p <= n:
while n % p == 0:
factors[p] = factors.get(p, 0) + 1
n //= p
p += 1
if n > 1:
factors[n] = factors.get(n, 0) + 1
return factors
def gcd_by_factoring(a, b):
a, b = abs(a), abs(b)
if a == 0:
return b
if b == 0:
return a
fa, fb = factorize(a), factorize(b)
result = 1
for p in fa.keys() & fb.keys():
result *= p ** min(fa[p], fb[p])
return result
print(factorize(1071)) # {3: 2, 7: 1, 17: 1}
print(gcd_by_factoring(1071, 462)) # 21
print(gcd_by_factoring(8, 15)) # 1When a or b is 1, factorize returns an empty dictionary. The intersection is then empty and the result is 1, which is correct.
This method explains the GCD well. It shows that the GCD collects exactly the prime factors the two numbers share. As a way to compute it, though, it is a dead end. No known classical algorithm factors large integers efficiently, and RSA cryptography depends on that being hard. Euclid's algorithm finds the GCD without factoring anything, and that is the reason it is so useful.
Common errors
- Assuming
gcd(a, b) <= min(a, b). This fails when one input is zero:gcd(0, 5) = 5. The bound holds only when both inputs are nonzero, and then it applies to their absolute values. - Returning a negative GCD. The GCD is nonnegative by definition.
gcd(-12, 18)is 6, not -6. - Treating
gcd(0, 0)as an error. It equals 0 by the standard convention. Code that raises an exception or loops forever on this input is wrong. - Testing divisibility with floats.
(a / d).is_integer()gives wrong answers for large integers because of floating-point rounding. Usea % d == 0. - Confusing coprime with prime. Coprime describes a pair of numbers. 9 and 28 are coprime, and neither one is prime.
- Mixing up GCD and LCM. The GCD divides both inputs. The least common multiple is divisible by both. A later chapter derives the LCM from the GCD.
Exercises
Exercise
List all positive common divisors of 36 and 60, then state gcd(36, 60). Check that every common divisor divides the GCD.
Show answer
Divisors of 36 are 1, 2, 3, 4, 6, 9, 12, 18, 36. Divisors of 60 are 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60. The common ones are 1, 2, 3, 4, 6, 12, so gcd(36, 60) = 12. Each of 1, 2, 3, 4, and 6 divides 12.
Exercise
Evaluate gcd(-42, 0), gcd(0, 0), gcd(17, 51), and gcd(-9, -28), and justify each using a fact from this chapter.
Show answer
gcd(-42, 0) = 42, because gcd(a, 0) = |a|. gcd(0, 0) = 0 by convention. gcd(17, 51) = 17, because 17 divides 51 (51 = 17 3), so the GCD is |17|. gcd(-9, -28) = gcd(9, 28) = 1, because sign does not matter and 9 = 3^2 and 28 = 2^2 7 share no prime. So -9 and -28 are coprime.
Exercise
Prove that if d divides both a and b, then d divides a - 3b. Then use this to explain why gcd(a, b) divides a - 3b.
Show answer
Write a = dk and b = dm for integers k and m. Then a - 3b = d*(k - 3m), and k - 3m is an integer, so d | (a - 3b). This is the linear-combination property with x = 1 and y = -3. gcd(a, b) is itself a common divisor of a and b, so the same argument shows it divides a - 3b.
Exercise
The gcdbrute function checks a == 0 and b == 0 before its loop. What would it return for gcdbrute(0, 9) without those checks, and why?
Show answer
It would return None. With a = 0, min(a, b) is 0, so range(0, 0, -1) is empty and the loop body never runs. The function then reaches its end with no return statement, so Python returns None. The correct answer is 9.
Exercise
For coprime inputs a and b with 1 < a < b, how many candidates does gcd_brute test? Why does this make it unusable for 40-digit inputs?
Show answer
It tests every d from a down to 1, which is a candidates, because no d > 1 divides both. For a 40-digit a, that is about 10^39 tests. At a billion tests per second that would still take more than 10^22 years.