Sub topic 1
Divisibility and Remainders
Prerequisites
This chapter assumes you can do basic integer arithmetic, use the modulo operator %, and read short Python functions with loops and lists.
Divisibility and the Modulo Operation
An integer d divides n when n = d * k for some integer k. In code, you test this with the remainder: n % d == 0. For example, 84 % 7 is 0, so 7 divides 84. 84 % 5 is 4, so 5 does not.
A common mistake is mixing up the order of the operands. n % d asks "what is left after dividing n by d?" It does not ask whether n divides d.
What Makes a Number Prime
A prime is an integer greater than 1 whose only positive divisors are 1 and itself. A composite is an integer greater than 1 that has at least one other divisor. The numbers 0 and 1 are neither prime nor composite. Forgetting this is the most common bug in primality code.
| n | Divisors | Type |
|---|---|---|
| 1 | 1 | neither |
| 7 | 1, 7 | prime |
| 12 | 1, 2, 3, 4, 6, 12 | composite |
Every Integer Factors Uniquely into Primes
The fundamental theorem of arithmetic says that every integer greater than 1 is a product of primes, and that this product is unique apart from the order of the factors. For example, 84 = 2 × 2 × 3 × 7, and no other set of primes multiplies to 84. This is why primes are called the building blocks of the integers.
Why the Primes Never Run Out
Euclid proved that there are infinitely many primes. Suppose the list p₁, …, pₖ contained every prime. Let N = p₁ × … × pₖ + 1. Dividing N by any pᵢ leaves remainder 1, so no prime on the list divides N. N still has a prime factor, so that factor must be a prime missing from the list. This contradicts the assumption that the list was complete.
Testing One Number with Trial Division
Trial division tests each candidate divisor d in turn. The loop can stop once d * d > n, because any composite n has a factor no larger than its square root. The next chapter explains why.
def is_prime(n):
if n < 2:
return False
d = 2
while d * d <= n:
if n % d == 0:
return False
d += 1
return True
print([k for k in range(20) if is_prime(k)]) # [2, 3, 5, 7, 11, 13, 17, 19]Exercise
Using Euclid's construction with the primes 2, 3, 5, 7, 11, 13, you get N = 30031. Is N prime? What does this tell you about the proof?
Show answer
No. 30031 = 59 × 509. The proof does not claim that N is prime. It only shows that N has a prime factor missing from the list, and here 59 and 509 are both missing.