Sub topic 6
Why You Only Need to Check Up to the Square Root
The previous chapter's trial-division test stopped as soon as d * d > n. This chapter shows why that stopping rule is correct, why it is the right place to stop, and how small implementation choices can quietly break it. It assumes you know the modulo operator, can read Python loops and functions, have met Big-O notation, and remember the definitions of prime and composite numbers from earlier chapters.
Divisors Come in Pairs
When d divides n, the quotient n // d also divides n. Divisors therefore come in pairs (d, n // d) whose product is n. Here are the pairs for 36:
| Small divisor `a` | Large divisor `b` | `a * b` |
|---|---|---|
| 1 | 36 | 36 |
| 2 | 18 | 36 |
| 3 | 12 | 36 |
| 4 | 9 | 36 |
| 6 | 6 | 36 |
Look at the left column. Every entry is at most 6, and 6 is the square root of 36. Moving down the table, the small divisor grows and the large divisor shrinks until they meet at the square root. After that point the pairs would only repeat in reverse order (9 × 4, 12 × 3, and so on).
So any divisor larger than the square root has a partner below it. If you scan the small side and find nothing, the large side has nothing to offer either.
The Proof
Claim. If n > 1 is composite, then n has a divisor d with 2 <= d <= √n.
Proof. Because n is composite, it can be written as n = a * b with 1 < a <= b < n. Suppose a > √n. Then b >= a > √n as well, so a * b > √n * √n = n. That contradicts a * b = n, so a <= √n. ∎
Turned around, the claim gives you the test: if no integer d with 2 <= d <= √n divides n, then n is prime. The bound is also tight. When n = p * p for a prime p, the only divisor besides 1 and n is p = √n itself. Any bound smaller than √n would miss it.
A stronger fact: the first divisor found is prime
Trial division counts upward from 2, so the first divisor it finds is the smallest divisor of n greater than 1. That divisor is always prime. If it were composite, it would have a smaller divisor greater than 1, and that smaller divisor would also divide n and would have been found first.
This has two practical consequences:
- Trial division does more than say "composite". It returns a prime factor, which you can divide out and repeat to get the full factorization.
- In principle you only need to test prime candidates
d. Testing 4, 6 or 9 is wasted work, because 2 or 3 would already have caught anynthat those numbers divide.
Turning the Bound into Code
This function returns the smallest prime factor of n. A result equal to n means n is prime.
def smallest_factor(n):
"""Return the smallest prime factor of n (n >= 2)."""
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 # no divisor up to sqrt(n): n is prime
for n in [2, 49, 91, 97, 1_000_003]:
print(n, smallest_factor(n))
# 2 2
# 49 7
# 91 7
# 97 97
# 1000003 1000003The condition d * d <= n is the square-root bound written in integer arithmetic. It has three useful properties:
- It uses
<=, so forn = 49the loop still testsd = 7. - It never touches floating point, so it stays exact for integers of any size.
- It re-evaluates the bound on every step without calling a square-root function.
Measuring the Savings
How much work does the bound save? Count the loop iterations for a prime, which is the worst case because the loop never exits early:
def count_naive(n):
steps = 0
for d in range(2, n):
steps += 1
if n % d == 0:
break
return steps
def count_sqrt(n):
steps = 0
d = 2
while d * d <= n:
steps += 1
if n % d == 0:
break
d += 1
return steps
n = 1_000_003 # the smallest prime above one million
print(count_naive(n)) # 1000001
print(count_sqrt(n)) # 999The work drops from about a million divisions to under a thousand. In general the naive loop costs O(n) and the bounded loop costs O(√n).
Common Errors
Using `<` instead of `<=`
def is_prime_buggy(n):
if n < 2:
return False
d = 2
while d * d < n: # bug: should be <=
if n % d == 0:
return False
d += 1
return True
print([k for k in [4, 9, 25, 49, 121] if is_prime_buggy(k)]) # [4, 9, 25, 49, 121]Every square of a prime gets reported as prime, because its only nontrivial divisor sits exactly at the bound. Ordinary random tests often miss this bug, since squares of primes are rare. Always include values like 4, 9, 25 and 49 in your test cases.
Off-by-one with `range` and a float square root
range(2, int(n ** 0.5)) stops before int(n ** 0.5), so it has the same defect as <. The correct form is range(2, math.isqrt(n) + 1).
Floating-point square roots on large integers
math.sqrt and n ** 0.5 convert n to a 64-bit float, which holds only 53 bits of precision. Above about 9 × 10¹⁵ the conversion itself can round:
import math
n = 10**16 - 1
print(int(math.sqrt(n))) # 100000000 (too large: 100000000**2 > n)
print(math.isqrt(n)) # 99999999 (exact floor of the square root)Here float(n) rounds up to exactly 1e16, and its square root is exactly 1e8. An overestimate like this only costs one extra iteration. For other values, though, rounding can go down and land one below the true root of a perfect square p * p. The loop then skips p and declares a composite number prime. Use math.isqrt (Python 3.8+) or the d * d <= n comparison. Both are exact for arbitrarily large integers.
Recomputing an expensive bound inside the loop
while d <= math.isqrt(n) is correct but recomputes the square root on every pass. Compute limit = math.isqrt(n) once before the loop, or use d * d <= n, which costs one multiplication.
Skipping Candidates That Cannot Matter
The fact that the first divisor found is prime lets you skip most candidates. A common middle ground handles 2 separately and then tests only odd d:
import math
def is_prime_odd(n):
if n < 2:
return False
if n % 2 == 0:
return n == 2
limit = math.isqrt(n)
for d in range(3, limit + 1, 2):
if n % d == 0:
return False
return True
print([k for k in range(30) if is_prime_odd(k)])
# [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]This halves the work. A further step, testing only d of the form 6k ± 1 after handling 2 and 3, removes another third of the candidates. Testing only true primes is the ideal, but it requires a precomputed list of primes up to √n. Producing that list is exactly the job of the sieve in the next chapter.
What O(√n) Really Means
O(√n) sounds cheap, but cost is usually measured by the size of the input, which is the number of digits or bits of n. A b-bit number has a square root of about 2^(b/2), so trial division is exponential in the bit length:
| `n` (approx.) | `√n` iterations, worst case | Practical? |
|---|---|---|
| 10⁶ | 10³ | instant |
| 10¹² | 10⁶ | milliseconds to seconds in Python |
| 10¹⁸ | 10⁹ | minutes in Python |
| 10⁴⁰ | 10²⁰ | never |
For one number up to about 10¹², trial division with the square-root bound is simple and fast enough. Beyond that, probabilistic tests such as Miller–Rabin take over. They are outside this tutorial.
Where the Bound Shows Up Again
The same argument drives the rest of this tutorial:
- The sieve's outer loop stops at
p * p <= n. Every composite up tonhas a prime factor no larger than√n, so onceppasses√n, every composite has already been crossed out. - Starting each pass at
p * p, the subject of a later chapter, rests on the same pairing idea. Any multiplek * pwithk < phas a smaller factorkand has already been handled. - Segmented sieves need only the base primes up to
√hito sieve any range ending athi.
In each case the reason is the one proved above: a composite number cannot hide all of its factors above its square root.
Exercise
For n = 221, list the values of d that smallest_factor(n) tests and say what it returns. What is the largest d it would test if 221 were prime?
Show answer
It tests d = 2, 3, ..., 13 and returns 13, because 221 = 13 × 17. Since isqrt(221) = 14 (14 × 14 = 196 ≤ 221 < 225 = 15 × 15), a prime n of that size would make the loop test up to d = 14.
Exercise
A colleague writes for d in range(2, int(n ** 0.5)): if n % d == 0: return False followed by return True (for n >= 2). Give the smallest input it gets wrong, and fix it.
Show answer
It reports 4 as prime: int(4 ** 0.5) = 2, so range(2, 2) is empty. It gets every square of a prime wrong, including 9, 25 and 49. The fix is for d in range(2, math.isqrt(n) + 1), which includes the square root and avoids float rounding.
Exercise
Explain why returning the first d with n % d == 0 always yields a prime, even though the loop also tests composite values such as 4 and 6.
Show answer
The first divisor found is the smallest divisor of n greater than 1. If it were composite, it would have a divisor e with 1 < e < d. Then e would also divide n, and since e < d the loop would have found e first. So a composite d can never be the first hit, and the composite candidates only cost time.
Exercise
You need to test one million numbers, each below 10**10, for primality. How large must your list of trial divisors be, and roughly how many divisions does each test need in the worst case if you use only primes?
Show answer
The divisors must reach isqrt(1010) = 105, so you need the primes up to 100,000. There are 9,592 of them, which is about 105 / ln(105) ≈ 8,686 by the prime number theorem. Each worst-case test therefore needs about 9,600 divisions, compared with about 50,000 using odd numbers only.