Sub topic 1
Divisors, Common Divisors, and the GCD
Prerequisites
This chapter assumes you know basic integer arithmetic and Python's // and % operators. You should also be able to read a short algebraic proof.
Divisors and the Greatest Common Divisor
An integer d divides a, written d | a, when a = d·k for some integer k. A common divisor of a and b is an integer that divides both of them. The greatest common divisor, gcd(a, b), is the largest common divisor.
Take 48 and 18 as an example:
| Number | Positive divisors |
|---|---|
| 48 | 1, 2, 3, 4, 6, 8, 12, 16, 24, 48 |
| 18 | 1, 2, 3, 6, 9, 18 |
The common divisors are 1, 2, 3 and 6, so gcd(48, 18) = 6. Every integer divides 0, so the convention is gcd(a, 0) = |a|.
Listing divisors becomes impractical once the numbers are large. Euclid's algorithm avoids listing them, and it depends on one fact about remainders.
Division with Remainder
For any integer a and any integer b > 0, there is exactly one pair of integers q and r such that a = b·q + r and 0 ≤ r < b. Here q is the quotient and r is the remainder, written a mod b.
a, b = 1071, 462
q, r = divmod(a, b)
print(q, r) # 2 147
print(a == b * q + r) # True
print(-7 % 3) # 2, Python keeps 0 <= r < bWhy gcd(a, b) Equals gcd(b, a mod b)
Let r = a mod b, so a = b·q + r.
- Suppose d | a and d | b. Then d divides a − b·q, which equals r. So every common divisor of a and b is also a common divisor of b and r.
- Suppose d | b and d | r. Then d divides b·q + r, which equals a. So every common divisor of b and r is also a common divisor of a and b.
Both pairs have exactly the same set of common divisors, so they have the same greatest one. Because r < b, applying this identity repeatedly makes the numbers smaller:
Exercise
Use the identity gcd(a, b) = gcd(b, a mod b) to compute gcd(252, 105), showing each remainder.
Show answer
252 = 2·105 + 42, so gcd(252, 105) = gcd(105, 42). 105 = 2·42 + 21, so this equals gcd(42, 21). 42 = 2·21 + 0, so this equals gcd(21, 0) = 21.
Exercise
In the proof, why does a common divisor d of b and r also divide a?
Show answer
Because a = b·q + r. If b = d·m and r = d·n, then a = d·(m·q + n), which is a multiple of d.