Sub topic 1
Divisibility and Remainders
Every prime test and every sieve in this tutorial comes down to one question: does one integer divide another exactly? This chapter makes that question precise and shows how Python answers it, including the edge cases that cause bugs later.
Prerequisites
This chapter assumes you can:
- Do integer arithmetic, including multiplication and integer division.
- Read and write simple Python functions, loops, and list comprehensions.
- Run a Python 3 script or use an interactive session.
Big-O notation is not needed yet. It appears in later chapters.
What "d divides n" Means
An integer d divides an integer n if there is an integer k with n = d * k. We write this as d | n, and we call d a divisor (or factor) of n, and n a multiple of d.
Some examples:
3 | 12because12 = 3 * 4.5 ∤ 12because no integerkmakes5 * k = 12.d | 0for every nonzerod, because0 = d * 0.1 | nandn | nfor everyn.
The last two facts matter in the next chapter. Every integer greater than 1 has at least two divisors, 1 and itself, and primes are the numbers that have no others.
The Division Algorithm
For any integer n and any positive integer d, there is exactly one pair of integers q (the quotient) and r (the remainder) such that:
n = d * q + r with 0 <= r < d
So d | n exactly when r = 0. Testing divisibility reduces to computing a remainder.
Remainders in Python
Python's % operator returns the remainder, and // returns the quotient. The built-in divmod returns both at once.
def divides(d, n):
"""Return True if d divides n exactly."""
if d == 0:
raise ValueError("divisor must be nonzero")
return n % d == 0
print(17 // 5, 17 % 5) # 3 2
print(divmod(17, 5)) # (3, 2)
print(divides(3, 12)) # True
print(divides(5, 12)) # False
print(divides(7, 0)) # True
# Python keeps the remainder's sign equal to the divisor's sign
print(-7 // 3, -7 % 3) # -3 2
print(7 % -3) # -2
# Every divisor of 36, found by brute force
print([d for d in range(1, 37) if divides(d, 36)])
# [1, 2, 3, 4, 6, 9, 12, 18, 36]The brute-force divisor list checks every candidate up to n. A later chapter shows why you can stop much earlier.
Common Errors
| Mistake | What happens | Fix |
|---|---|---|
| Writing `n / d == int(n / d)` | `/` returns a float, which loses precision for large integers | Use `n % d == 0` |
| Calling `n % 0` | Raises `ZeroDivisionError` | Check for `d == 0` first, or never generate it |
| Assuming `%` matches C or Java on negatives | In C and Java, `-7 % 3` is `-1`. In Python it is `2` | Rely on `% d == 0`, which gives the same answer in every language |
| Using `math.fmod` for integers | `math.fmod` returns a float and keeps the sign of `n` | Use `%` for integer work |
Exercises
Exercise
Compute divmod(-17, 5) in Python and check that the result satisfies n = d * q + r with 0 <= r < d.
Show answer
divmod(-17, 5) is (-4, 3). Check: 5 * (-4) + 3 = -20 + 3 = -17, and 0 <= 3 < 5.
Exercise
Using the divides function from this chapter, write a one-line expression that lists every divisor of 28, then say which of those divisors other than 28 add up to 28.
Show answer
[d for d in range(1, 29) if divides(d, 28)] gives [1, 2, 4, 7, 14, 28]. The divisors other than 28 are 1 + 2 + 4 + 7 + 14 = 28, so 28 equals the sum of its other divisors.
Exercise
Why is n % d == 0 safer than n / d == n // d for testing divisibility of large integers?
Show answer
The / operator converts to a 64-bit float, which holds only about 15 to 17 significant digits, so a nonzero fractional part can round away and the comparison gives a wrong True. The % operator works on exact integers of any size.