Primality test (trial division)
Divide n by 2, 3, … up to √n; if none of them divides n, n is prime.
If n = a·b and both factors were larger than √n, their product would exceed n. So every composite number has a
divisor ≤ √n, and it is enough to try d = 2, 3, … while d·d ≤ n.
- Time:
O(√n) - Space:
O(1) - Johnsonbaugh, chapter 5
- Grimaldi, chapter 4
97 is prime: only 2 to 9 are tried, because 10 × 10 is more than 97.
def is_prime(n):if n < 2:return Falsed = 2while d * d <= n:if n % d == 0:return Falsed = d + 1return True
Start
n97
d—
Local variables
n97
Orange = changed in this step
Call stack
- is_prime()line 1
Step 1 of 29
Explanation
The idea
If n = a·b and both factors were larger than √n, their product would exceed n. So every composite number has a
divisor ≤ √n, and it is enough to try d = 2, 3, … while d·d ≤ n.
Cost
At most √n divisions. For numbers with hundreds of digits (like RSA keys) that is far too slow, and probabilistic
tests such as Miller–Rabin are used instead.
What to watch in the trace
- The
dcard is the current divisor; see where the work stops. - "The square of a prime" shows why the condition is
≤.