Sub topic 1
Divisibility and Remainders
Before you can say what a prime number is, you need a precise idea of what it means for one integer to divide another. This chapter defines divisibility and the remainder of a division. It also covers how Python's % and // operators behave, including the edge cases that cause bugs in prime-related code. Every algorithm later in this tutorial, from trial division to the segmented sieve, is built on these operations.
Prerequisites
This chapter assumes you are comfortable with:
- Integer arithmetic: addition, multiplication, and long division with a quotient and remainder.
- Reading and writing short Python functions with loops, conditionals, and lists.
- Running Python 3 code, either in a script or an interactive shell.
Big-O notation is not needed yet. It appears in later chapters on sieve complexity.
What It Means for One Integer to Divide Another
Let a and b be integers with a not equal to zero. We say a divides b, written a | b, if there is an integer k such that b = a * k. In that case, a is a divisor (or factor) of b, and b is a multiple of a.
Some examples:
3 | 12, because12 = 3 * 4.5does not divide12, because no integerkgives5 * k = 12.7 | 0, because0 = 7 * 0. Every nonzero integer divides zero.-4 | 12, because12 = (-4) * (-3). Divisibility ignores sign.1 | bandb | bfor every nonzerob. These are the trivial divisors.
The definition never mentions fractions. Divisibility is a statement about integers only, and it is either true or false. That makes it a natural fit for the integer operators every programming language provides.
Basic properties
These facts follow directly from the definition. Later chapters rely on them without restating them.
| Property | Statement | Why it holds | Column | Column | Column | Column | Column | Column | Column | Column | Column |
|---|---|---|---|---|---|---|---|---|---|---|---|
| Transitivity | If `a \ | b` and `b \ | c`, then `a \ | c` | `b = a*j`, `c = b*k`, so `c = a*(j*k)` | ||||||
| Linear combinations | If `a \ | b` and `a \ | c`, then `a \ | (x*b + y*c)` for any integers `x`, `y` | `x*a*j + y*a*k = a*(x*j + y*k)` | ||||||
| Size bound | If `a \ | b` and `b > 0`, then `\ | a\ | <= b` | `b = \ | a\ | * \ | k\ | ` with `\ | k\ | >= 1` |
| Multiples | `a` divides `a`, `2a`, `3a`, ... | Each is `a * k` for an integer `k` |
The linear combination property is the one you will use most. For example, if d divides both n and n + 1, then d divides their difference, which is 1. So d must be 1 or -1. Consecutive integers share no common factor other than 1. This exact argument appears again in Euclid's proof that the primes never run out.
The Division Algorithm
Most pairs of integers do not divide evenly. The division algorithm describes what happens in general:
For any integer b and any positive integer a, there are unique integers q (the quotient) and r (the remainder) such that
b = q * a + r and 0 <= r < a.
Dividing 17 by 5 gives 17 = 3 * 5 + 2, so q = 3 and r = 2. The remainder is always in the range 0 to a - 1, so there are exactly a possible remainders when dividing by a.
This gives the practical test for divisibility: a divides b exactly when the remainder is zero. If r = 0, then b = q * a, which matches the definition. If r is between 1 and a - 1, then b sits strictly between two consecutive multiples of a and cannot be one.
Remainders in Python
Python gives you two operators that implement the division algorithm:
b // ais floor division. It returns the quotient rounded down toward negative infinity.b % ais the modulo operator. It returns the remainder.divmod(b, a)returns both as a tuple(q, r).
Python guarantees that (b // a) * a + (b % a) == b for every pair of integers with a != 0. A divisibility test is one line:
def divides(a, b):
"""Return True if a divides b. The divisor a must be nonzero."""
if a == 0:
raise ValueError("divisor must be nonzero")
return b % a == 0
print(divides(3, 12)) # True
print(divides(5, 12)) # False
print(divides(7, 0)) # True
print(divides(-4, 12)) # TrueThe explicit check for zero matters. Without it, b % 0 raises ZeroDivisionError, which is correct behavior, but a clear message makes the mistake easier to find.
Negative numbers
The division algorithm above assumes a positive divisor and produces a remainder in [0, a). Python extends this rule: the result of % always has the same sign as the divisor (or is zero). Many other languages behave differently, and this is a common source of bugs when porting code.
import math
for b in (17, -17):
q, r = divmod(b, 5)
print(b, "=", q, "* 5 +", r, "->", q * 5 + r == b)
print(17 % -5) # -3: sign follows the divisor
print(math.fmod(-17, 5)) # -2.0: sign follows the dividend, like COutput:
17 = 3 * 5 + 2 -> True
-17 = -4 * 5 + 3 -> True
-3
-2.0| Expression | Python `%` | C, C++, Java, JavaScript `%` | Python `math.fmod` |
|---|---|---|---|
| `17 % 5` | `2` | `2` | `2.0` |
| `-17 % 5` | `3` | `-2` | `-2.0` |
| `17 % -5` | `-3` | `2` | `2.0` |
For divisibility tests, the sign difference is harmless: b % a == 0 gives the same answer in every language, because zero has no sign. The difference matters when you use the remainder as an index or an offset, which the segmented sieve does. In this tutorial all sieve inputs are non-negative, so Python's rule and the textbook rule agree.
Modular Arithmetic Shortcuts
Remainders behave well under addition and multiplication. For any positive modulus m:
(x + y) % m == ((x % m) + (y % m)) % m(x * y) % m == ((x % m) * (y % m)) % m
This lets you reason about divisibility without computing large numbers. To check whether 3 divides 10**20 + 2, note that 10 % 3 == 1, so 10**20 % 3 == 1, and the sum leaves remainder (1 + 2) % 3 == 0. So 3 divides it. Python's built-in pow(base, exp, mod) uses this property to compute large powers modulo m quickly.
print((10**20 + 2) % 3) # 0
print(pow(10, 20, 3)) # 1, computed without building 10**20Multiples and Rounding to the Next Multiple
A sieve works by visiting every multiple of a number p: p, 2p, 3p, and so on. In Python, range(start, stop, p) produces an arithmetic sequence with step p. If start is a multiple of p, every value it produces is also a multiple of p.
Often you need the first multiple of p that is at least some lower bound lo. Floor division gives the answer. Adding p - 1 before dividing turns floor division into ceiling division for non-negative lo:
def first_multiple_at_least(p, lo):
"""Smallest multiple of p that is >= lo, for p > 0 and lo >= 0."""
return ((lo + p - 1) // p) * p
print(first_multiple_at_least(7, 100)) # 105
print(first_multiple_at_least(5, 100)) # 100
print(list(range(first_multiple_at_least(7, 100), 130, 7))) # [105, 112, 119, 126]When lo is already a multiple of p, adding p - 1 does not reach the next multiple, so the result is lo itself. Otherwise it rounds up. An equivalent expression is -(-lo // p) * p, which uses Python's floor-toward-negative-infinity behavior to round up. The segmented sieve chapter uses the first form.
Divisors Come in Pairs
If a * k = n, then both a and k divide n. Every divisor therefore has a partner. For n = 36:
| Divisor `a` | Partner `36 // a` |
|---|---|
| 1 | 36 |
| 2 | 18 |
| 3 | 12 |
| 4 | 9 |
| 6 | 6 |
Listing all divisors by brute force is straightforward:
def divisors(n):
"""All positive divisors of n, for n >= 1, by testing every candidate."""
return [d for d in range(1, n + 1) if n % d == 0]
print(divisors(36)) # [1, 2, 3, 4, 6, 9, 12, 18, 36]
print(divisors(13)) # [1, 13]The output for 13 contains only the trivial divisors, 1 and 13 itself. Numbers like that are the subject of the next chapter. In the table for 36, the left column stops at 6 while the right column keeps going. That pattern is what makes fast primality testing possible, and a later chapter explains it.
Common Errors
- Dividing by zero.
n % 0raisesZeroDivisionError. Loops that test candidate divisors should start at1or2, never0. - Using
/instead of//. You get floats, then rounding errors for large inputs, andrangeraisesTypeErrorwhen given a float. - Assuming C-style signs. In Python
-7 % 3is2, not-1. Code translated between languages can produce different offsets for negative inputs. - Forgetting that 0 is divisible by everything. A check like "
n % d == 0meansnis composite" misclassifies0. Prime-testing functions should rejectn < 2before any division. - Off-by-one in ranges.
range(1, n)excludesn. When a bound is inclusive, writerange(1, n + 1).
Exercise
Without running code, give the values of divmod(-23, 6) and -23 % -6 in Python, and check each against the identity q * a + r == b.
Show answer
divmod(-23, 6) is (-4, 1), because -4 6 + 1 = -23 and the remainder 1 has the sign of the divisor 6. For -23 % -6, the floor quotient is 3 (since -23 / -6 is about 3.83, rounded down to 3), and 3 -6 = -18, so the remainder is -23 - (-18) = -5. It has the sign of the divisor -6, and 3 * -6 + (-5) = -23.
Exercise
Suppose d divides both 91 and 65. Using only the linear combination property, show that d must divide 13. What does this tell you about the common divisors of 91 and 65?
Show answer
Since d divides 91 and 65, it divides 91 - 65 = 26, then 65 - 2 26 = 13. So every common divisor of 91 and 65 divides 13. The positive divisors of 13 are 1 and 13, and 13 does divide both (91 = 7 13, 65 = 5 * 13), so the positive common divisors are exactly 1 and 13.
Exercise
Write a function lastmultipleat_most(p, hi) that returns the largest multiple of p that is less than or equal to hi, for p > 0 and hi >= 0. What does it return for (7, 130) and (5, 100)?
Show answer
def lastmultipleat_most(p, hi): return (hi // p) p. Floor division already rounds down, so no adjustment is needed. It returns 126 for (7, 130), since 130 // 7 is 18 and 18 7 = 126, and 100 for (5, 100).