Sub topic 5
Testing One Number with Trial Division
This chapter assumes you know the modulo operator (%), can read Python loops and functions, and have seen Big-O notation. It also uses the definition from earlier chapters: a prime is an integer greater than 1 whose only positive divisors are 1 and itself.
The idea
Trial division answers one question: is this single number n prime? It tries possible divisors one at a time. If any divisor d with 1 < d < n gives n % d == 0, then n is composite. If no candidate divides n, then n is prime.
This is the most direct way to apply the definition, and for one number of moderate size it is often all you need.
A first, naive version
The simplest version checks every candidate from 2 up to n - 1:
def is_prime_naive(n):
if n < 2:
return False
for d in range(2, n):
if n % d == 0:
return False
return True
print([k for k in range(20) if is_prime_naive(k)]) # [2, 3, 5, 7, 11, 13, 17, 19]This gives correct answers, but it is slow. For a prime n, it performs n - 2 divisions, so the cost is O(n). Testing a prime near one billion would take about a billion modulo operations.
Stopping early
You do not need to check every candidate. If n has a divisor d, then n // d is also a divisor, and both cannot be larger than the square root of n. So if no divisor turns up by the time d * d exceeds n, none exists. The next chapter proves this bound carefully. Here we use it:
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]The worst case now costs about √n divisions, so the time is O(√n). For n near one billion, that is roughly 31,623 divisions instead of a billion.
How the loop behaves on real inputs
| n | Divisors tried | Result | Reason |
|---|---|---|---|
| 1 | none | False | Fails the `n < 2` guard |
| 2 | none | True | 2 * 2 > 2, so the loop never runs |
| 49 | 2 to 7 | False | 49 % 7 == 0 |
| 97 | 2 to 9 | True | 10 * 10 > 97, and no divisor found |
| 1000 | 2 | False | Even numbers exit at once |
Composite numbers usually exit quickly because most have a small factor. Primes cost the most, since the loop has to run all the way to √n.
Common errors
- Missing the
n < 2guard. Without it, 0 and 1 pass straight through the loop and come back as prime. Negative numbers do too. - Writing
d * d < ninstead of<=. Perfect squares of primes such as 4, 9, and 25 are then reported as prime, because their only small factor is exactly √n. - Using
math.sqrtwith floats. For very large integers,int(math.sqrt(n))can round wrongly. Used * d <= normath.isqrt(n), which work in exact integer arithmetic. - Calling it in a loop over a big range. Testing every number up to N costs about O(N√N) in total. Once you need many primes, the sieve covered in later chapters is far faster.
Exercise
Suppose the loop condition is mistakenly written as while d * d < n:. What does is_prime(25) return, and why?
Show answer
It returns True, which is wrong. The loop runs for d = 2, 3, 4, since 5 * 5 = 25 is not less than 25. None of 2, 3, or 4 divides 25, so the function never tests d = 5, the only prime factor.
Exercise
About how many modulo operations does is_prime perform on the prime 1,000,003, and on the composite 1,000,002?
Show answer
For 1,000,003 it tries d = 2 through 1000, since 1001 * 1001 > 1,000,003. That is 999 operations. For 1,000,002 it stops after one operation, because the number is even and d = 2 divides it.