Sub topic 5
Testing One Number with Trial Division
This chapter assumes you can write Python functions with loops and conditionals, you know that n % d == 0 means d divides n, and you are comfortable with introductory Big-O notation. It also uses the definition of a prime from earlier: an integer greater than 1 whose only positive divisors are 1 and itself.
Trial division is the most direct primality test. You try candidate divisors one by one. If any of them divides n evenly, n is composite. If none does, n is prime. The idea is simple, but the details decide whether it is correct and fast: where the loop starts, where it stops, which candidates it skips, and how it handles inputs like 0, 1, 2, and negative numbers.
The working model
A primality test is a function that takes an integer n and returns True if n is prime and False otherwise. Trial division answers by searching for a witness. A witness is a divisor d with 1 < d < n and n % d == 0. One witness proves that n is composite. If the search turns up no witness, n is prime.
Two questions shape every version of the algorithm:
- Which candidates
ddo you have to try? - When can you stop?
The rest of the chapter answers those two questions more and more tightly.
The naive version
The literal reading of the definition says to check every d 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 version is correct, and its correctness is easy to see, so it is a good reference implementation for testing faster versions. It is also slow. For a prime n it performs n - 2 divisions, so it runs in O(n) time.
Notice how it handles the small cases. For n = 2, range(2, 2) is empty, so the loop never runs and the function returns True. For n = 3, the loop tries only d = 2. The guard n < 2 matters. Without it, 0 and 1 would also produce an empty loop and be reported as prime, which is wrong.
Stopping at the square root
Divisors come in pairs. If n = a * b with a <= b, then a * a <= a * b = n, so a <= √n. Every composite number therefore has a divisor no larger than its square root. If no d with d * d <= n divides n, then no divisor exists at all. 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 loop condition is d * d <= n, not d * d < n. Take n = 25. The only witness is 5, and 5 * 5 == 25. A strict < would stop at d = 4 and wrongly report 25 as prime. Perfect squares of primes (4, 9, 25, 49, ...) are the standard test cases for this off-by-one error.
The cost is now about √n divisions in the worst case, so the running time is O(√n). For a prime near 10¹², that is roughly a million divisions instead of a trillion.
Why `d * d <= n` instead of `math.sqrt`
You will often see for d in range(2, int(math.sqrt(n)) + 1). For small n it works. For large n it is risky. math.sqrt returns a 64-bit float, and once n grows past about 2⁵², the float result can land slightly below the true root. Truncating that with int() gives an answer one too small, and the loop skips the very divisor it needed. Comparing d * d <= n uses exact integer arithmetic, so it cannot go wrong this way. If you prefer a precomputed bound, use math.isqrt(n), which returns the exact integer square root:
import math
def is_prime_isqrt(n):
if n < 2:
return False
for d in range(2, math.isqrt(n) + 1):
if n % d == 0:
return False
return True
print(is_prime_isqrt(97), is_prime_isqrt(91)) # True FalseSkipping candidates you don't need
After you test d = 2, every other even candidate is wasted work. If 4 divided n, then 2 would already have divided it. You can handle 2 separately and then test only odd numbers:
def is_prime_odd(n):
if n < 2:
return False
if n % 2 == 0:
return n == 2
d = 3
while d * d <= n:
if n % d == 0:
return False
d += 2
return True
print([k for k in range(30) if is_prime_odd(k)]) # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]The line return n == 2 handles two cases at once. It returns True for 2, the only even prime, and False for every other even number.
The same idea extends further. Every integer has the form 6k + r with r from 0 to 5. The forms 6k, 6k + 2, 6k + 3, and 6k + 4 are divisible by 2 or 3. So every prime greater than 3 has the form 6k + 1 or 6k + 5, which is the same as 6k - 1. After handling 2 and 3 separately, you only need to test d = 5, 7, 11, 13, 17, 19, ..., which means pairs (d, d + 2) with d going up by 6:
def is_prime_6k(n):
if n < 2:
return False
if n < 4:
return True # 2 and 3
if n % 2 == 0 or n % 3 == 0:
return False
d = 5
while d * d <= n:
if n % d == 0 or n % (d + 2) == 0:
return False
d += 6
return True
print([k for k in range(50) if is_prime_6k(k)])
# [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]There is a subtle point here. The loop checks d * d <= n but also tests d + 2, and (d + 2)² can exceed n. That extra test is harmless. If d + 2 divides n and d + 2 < n, then n really is composite. And d + 2 cannot equal n at that point, because d * d <= n with d >= 5 means n is much larger than d + 2.
These tricks only change the constant factor. Each version is still O(√n).
| Version | Candidates tried for a prime n | Divisions for a prime near 10¹² |
|---|---|---|
| Naive, 2 to n − 1 | n − 2 | about 10¹² |
| Square root bound | about √n | about 1,000,000 |
| Odd candidates only | about √n / 2 | about 500,000 |
| 6k ± 1 candidates | about √n / 3 | about 333,000 |
Verifying the variants against each other
Fast versions bring new edge cases with them. The cheapest protection is to compare every version against the naive one over a range that includes negatives, 0, 1, 2, 3, and plenty of perfect squares:
def is_prime_naive(n):
if n < 2:
return False
for d in range(2, n):
if n % d == 0:
return False
return True
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
def is_prime_odd(n):
if n < 2:
return False
if n % 2 == 0:
return n == 2
d = 3
while d * d <= n:
if n % d == 0:
return False
d += 2
return True
def is_prime_6k(n):
if n < 2:
return False
if n < 4:
return True
if n % 2 == 0 or n % 3 == 0:
return False
d = 5
while d * d <= n:
if n % d == 0 or n % (d + 2) == 0:
return False
d += 6
return True
for k in range(-10, 3000):
expected = is_prime_naive(k)
assert is_prime(k) == expected, k
assert is_prime_odd(k) == expected, k
assert is_prime_6k(k) == expected, k
print("all variants agree")Returning the witness, not just a boolean
Often you want to know why a number is composite. A small change returns the smallest divisor greater than 1. If that divisor is n itself, n is prime. The first witness trial division finds is always the smallest prime factor, because any smaller composite divisor would have a prime factor that the loop reached earlier.
def smallest_factor(n):
if n < 2:
raise ValueError("n must be at least 2")
d = 2
while d * d <= n:
if n % d == 0:
return d
d += 1
return n
print(smallest_factor(91), smallest_factor(97), smallest_factor(1001)) # 7 97 7Raising an error for n < 2 is a deliberate choice. 0, 1, and negative numbers have no smallest prime factor, so returning a number would hide a bug in the caller.
Cost: best case, worst case, and input size
Trial division stops at the first witness, so its running time depends heavily on the input:
- Even numbers stop after one division.
- Most composites have a small factor and stop early. A third of all integers are divisible by 3, a fifth by 5, and so on.
- The worst cases are primes and products of two primes close to √n, such as
999983 * 1000003. These run the full √n loop.
O(√n) sounds fast, but measure it against the size of the input. A number with b bits has √n ≈ 2^(b/2), so the running time is exponential in the number of digits. A 64-bit prime needs about 4 × 10⁹ divisions even with the 6k ± 1 trick, which takes seconds to minutes in Python. A 1024-bit number is completely out of reach. For large inputs, real systems use probabilistic tests such as Miller–Rabin, which run in time polynomial in b.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Missing `n < 2` guard | 0, 1, or negatives reported prime | Return `False` before the loop |
| `d * d < n` instead of `<=` | 4, 9, 25, 49 reported prime | Use `<=` |
| Float bound `int(math.sqrt(n))` | Rare wrong answers for very large n | Use `d * d <= n` or `math.isqrt` |
| Odd-only loop without even check | Even numbers reported prime | Test `n % 2` first, return `n == 2` |
| Starting the loop at `d = 1` | Every number reported composite | Start at 2 |
Exercise
A colleague writes for d in range(2, int(n ** 0.5)): if n % d == 0: return False followed by return True, with a correct n < 2 guard. Give the smallest input it gets wrong and explain the bug.
Show answer
The smallest wrong input is 4. int(4 ** 0.5) is 2, and range(2, 2) is empty, so the function returns True. The upper bound of range is exclusive, so the loop never tries d = √n itself. Every square of a prime (4, 9, 25, ...) is misclassified. The fix is range(2, math.isqrt(n) + 1).
Exercise
For n = 1,000,003 (a prime), about how many trial divisions do the square root version and the 6k ± 1 version perform?
Show answer
√1,000,003 is about 1000. The square root version tries d = 2 through 1000, about 999 divisions. The 6k ± 1 version does 2 divisions for 2 and 3, then 2 per loop step for d = 5, 11, ..., up to about 1000, which is about 166 steps, so roughly 334 divisions in total.
Exercise
Modify smallest_factor to return the full list of prime factors of n in increasing order (for example 84 gives [2, 2, 3, 7]). Why is it safe to keep dividing by the same d before moving on?
Show answer
Loop with while d * d <= n: and inside it while n % d == 0: factors.append(d); n //= d, then d += 1. After the outer loop, if n > 1, append n, because the leftover value is prime. Dividing out d completely before moving on means no composite d can ever divide the remaining n, since all of its prime factors were removed earlier. So every d that gets appended is prime.