Sub topic 2
Division with Remainder
Every step of Euclid's algorithm is one division with remainder. This chapter states the theorem behind that operation, proves it, and shows how programming languages implement it. Languages disagree about negative operands, and that disagreement causes real bugs in GCD code.
This chapter assumes you know basic integer arithmetic, the % and // operators in Python, and the definition of divisibility from the previous chapter: b divides a (written b | a) when a = b * k for some integer k.
The Division Algorithm
The division algorithm is a theorem. Despite the name, it does not describe a procedure. It says:
For any integer a and any integer b > 0, there exist unique integers q and r such that
a = b * q + r and 0 <= r < b.
Here a is the dividend, b the divisor, q the quotient, and r the remainder. The condition 0 <= r < b matters. Without it, 17 = 5 * 2 + 7 and 17 = 5 * 4 - 3 would also be valid ways to write 17, and "the remainder" would not mean anything.
Some examples with b = 5:
| a | q | r | Check |
|---|---|---|---|
| 17 | 3 | 2 | 5 * 3 + 2 = 17 |
| 5 | 1 | 0 | 5 * 1 + 0 = 5 |
| 3 | 0 | 3 | 5 * 0 + 3 = 3 |
| 0 | 0 | 0 | 5 * 0 + 0 = 0 |
| -17 | -4 | 3 | 5 * (-4) + 3 = -17 |
The last row trips people up. The remainder must be non-negative, so the quotient for -17 is -4, not -3. Choosing -3 would force r = -2, which breaks 0 <= r < b.
Remainder zero means divisibility
The theorem connects directly to the previous chapter: b | a exactly when the remainder is 0. If r = 0, then a = b * q, which is the definition of divisibility. In the other direction, if a = b * k, then q = k, r = 0 satisfies the theorem, and uniqueness says it is the only solution. This is why Euclid's algorithm stops when a remainder hits zero: at that point the last divisor divides the previous number exactly.
Proving Existence and Uniqueness
Both halves of the proof are short. The GCD correctness argument later in the tutorial relies on each of them.
Existence
Consider the set
S = { a - b * q : q is an integer, and a - b * q >= 0 }.
S is non-empty. If a >= 0, take q = 0 to get a in S. If a < 0, take q = a to get a - b * a = a * (1 - b), which is non-negative because a < 0 and 1 - b <= 0.
By the well-ordering principle (every non-empty set of non-negative integers has a smallest element), S has a least element. Call it r, and call its quotient q. By construction r >= 0 and a = b * q + r.
Suppose r >= b. Then r - b = a - b * (q + 1) is non-negative, so it belongs to S, and it is smaller than r. That contradicts the choice of r as the smallest element. So r < b.
Uniqueness
Suppose a = b * q + r = b * q' + r' with both remainders in [0, b). Subtracting gives
b * (q - q') = r' - r.
The right side lies strictly between -b and b, because both remainders do. The left side is a multiple of b. The only multiple of b strictly between -b and b is 0, so r' = r and therefore q' = q.
Computing q and r by Repeated Subtraction
The existence proof suggests a procedure. Start with r = a. Subtract b while r is too large, and add b while r is negative. The quotient counts the steps.
def divide(a, b):
"""Return (q, r) with a == b*q + r and 0 <= r < b, for b > 0."""
if b <= 0:
raise ValueError("divisor must be positive")
q, r = 0, a
while r >= b:
r -= b
q += 1
while r < 0:
r += b
q -= 1
return q, r
for a in (17, 5, 3, 0, -17):
q, r = divide(a, 5)
assert (q, r) == divmod(a, 5)
assert a == 5 * q + r and 0 <= r < 5
print(f"{a} = 5 * {q} + {r}")Output:
17 = 5 * 3 + 2
5 = 5 * 1 + 0
3 = 5 * 0 + 3
0 = 5 * 0 + 0
-17 = 5 * -4 + 3The loop runs about |q| times. For divide(10**12, 7) it would run roughly 143 billion iterations, while hardware division or Python's big-integer division finishes almost instantly. Euclid's original GCD method works at this level of repeated subtraction, which is why it can be slow. A later chapter compares it with the division-based form.
Remainders repeat with period b
As a increases by 1, the remainder increases by 1 until it reaches b - 1, then wraps to 0. With the non-negative convention, the pattern continues unchanged through zero into the negative numbers.
Negative Operands: Three Conventions
The theorem as stated requires b > 0. Real code also passes negative divisors, and languages answer differently. There are three common conventions.
- Floored division rounds the quotient toward negative infinity. The remainder has the sign of the divisor. Python's
//,%, anddivmoduse this, as do Ruby and Haskell'sdiv/mod. - Truncated division rounds the quotient toward zero. The remainder has the sign of the dividend. C (since C99), C++, Java, JavaScript, Go, and Rust's
%use this. - Euclidean division always gives
0 <= r < |b|. This matches the theorem for any non-zerob. Rust offers it asdiv_euclidandrem_euclid.
All three satisfy a = b * q + r and |r| < |b|. They differ only in the sign of r and, as a result, in q.
| a | b | Floored (Python) q, r | Truncated (C, Java) q, r | Euclidean q, r |
|---|---|---|---|---|
| 17 | 5 | 3, 2 | 3, 2 | 3, 2 |
| -17 | 5 | -4, 3 | -3, -2 | -4, 3 |
| 17 | -5 | -4, -3 | -3, 2 | -3, 2 |
| -17 | -5 | 3, -2 | 3, -2 | 4, 3 |
When b > 0, floored and Euclidean division agree. This is why Python's % with a positive modulus always returns a value in [0, b), which is convenient for modular arithmetic.
The following code implements the other two conventions on top of Python's floored divmod, so you can compare them directly:
def trunc_divmod(a, b):
"""Quotient rounded toward zero, remainder has the sign of a (C/Java style)."""
if b == 0:
raise ZeroDivisionError("division by zero")
q = abs(a) // abs(b)
if (a < 0) != (b < 0):
q = -q
return q, a - b * q
def euclid_divmod(a, b):
"""Remainder always satisfies 0 <= r < |b|."""
if b == 0:
raise ZeroDivisionError("division by zero")
q, r = divmod(a, b) # floored: r has the sign of b
if r < 0: # only possible when b < 0
q, r = q + 1, r - b # r - b adds |b|
return q, r
for a, b in [(17, 5), (-17, 5), (17, -5), (-17, -5)]:
for name, f in [("floor", divmod), ("trunc", trunc_divmod), ("euclid", euclid_divmod)]:
q, r = f(a, b)
assert a == b * q + r and abs(r) < abs(b)
print(f"{name:6} {a:4} {b:3} -> q={q:3}, r={r:3}")What This Means for GCD Code
For computing a GCD, the sign of the remainder never changes the answer. The divisors of r and -r are the same, so gcd ignores signs. Two practical consequences follow.
- Any convention keeps the algorithm working. Each convention gives
|r| < |b|, so the absolute values still shrink with every step. However, if you writea % bwith a negativebin Python, intermediate remainders can be negative, and the loop could end with a negative "GCD". The standard fix is to takeabsof both inputs once, before the loop. The chapter on zero and negative inputs covers this in detail. - The equation
r = a - b * qis what the proofs use. The next chapter shows that any common divisor ofaandbalso dividesa - b * q. That argument needs only the equation, not the sign convention, which is why the invariantgcd(a, b) = gcd(b, a mod b)holds in every language.
Division by zero is the one case the theorem excludes entirely. With b = 0 no remainder satisfies 0 <= r < 0, and Python raises ZeroDivisionError. Euclid's algorithm avoids this because it checks b != 0 before every division and returns a when b reaches zero.
Common Errors
- Assuming
%is never negative. That holds in Python only for a positive divisor. In C, Java, and JavaScript,-7 % 3is-1, not2. - Mixing quotient and remainder conventions. Pairing Python's
//with a C-style remainder breaksa == b * q + r. Usedivmodto get a matched pair. - Forgetting
r < bin proofs. Writinga = b * q + rwithout the bound proves nothing about termination. - Using float division for large integers. See the warning above.
Exercise
Find q and r under the Euclidean convention (0 <= r < |b|) for a = -23, b = 7 and for a = 23, b = -7. Then give Python's divmod result for each pair.
Show answer
For (-23, 7): -23 = 7 (-4) + 5, so q = -4, r = 5. Python's divmod(-23, 7) gives (-4, 5), the same result, because the divisor is positive. For (23, -7): 23 = (-7) (-3) + 2, so q = -3, r = 2. Python's divmod(23, -7) gives (-4, -5), since floored division gives the remainder the sign of the divisor. Check: (-7) * (-4) + (-5) = 28 - 5 = 23.
Exercise
The uniqueness proof uses the fact that r' - r lies strictly between -b and b. Explain why that fact fails if the remainder condition is loosened to 0 <= r <= b, and give a concrete example of two different (q, r) pairs for a = 10, b = 5.
Show answer
With 0 <= r <= b, the difference r' - r can equal b or -b, and those are non-zero multiples of b, so q - q' can be ±1. For a = 10, b = 5, both (q, r) = (2, 0) and (q, r) = (1, 5) satisfy 10 = 5q + r with 0 <= r <= 5, so the remainder is no longer unique.
Exercise
Write a Python function mod_nonneg(a, m) that returns the remainder in [0, |m|) for any non-zero m, without calling divmod with a negative m. Check it on (-17, 5), (17, -5), and (-17, -5).
Show answer
def modnonneg(a, m): return a % abs(m). With a positive modulus, Python's % already returns a value in [0, |m|). Results: modnonneg(-17, 5) = 3, modnonneg(17, -5) = 2, modnonneg(-17, -5) = 3. These match the remainders in the Euclidean column of the conventions table.