Prime numbers
easy 15 minA prime is a whole number above 1 whose only divisors are 1 and itself.
Video lesson · Chapter 1 of 6
A prize on a prime ticket
Prime numbers
1:26Reel
Read caption
Sol prints prime tickets through twenty with a sieve and learns why crossing can stop at the square root. Mark the multiples. Print the survivors.
How it works
Step through the idea, or press Play.
Test up to the square root. If n = a × b, one of a or b is at most √n, so checking divisors up to √n is enough
Understand it
Start here
What a prime number is
A prime number is a natural number greater than 1 with exactly two distinct positive divisors: 1 and itself. A number above 1 that is not prime is composite: it can be written as a product of smaller numbers. Primes are the atoms of arithmetic; they cannot be broken down any further.
The definition
1 is not prime
It has only one divisor. Calling it prime would also break unique factorization: .
2 is special
The smallest prime and the only even one. Every other even number is divisible by 2, so code checks 2 once and then tests only odd numbers.
Composites split
, like a molecule built from prime atoms. Every composite has a prime factor no bigger than its square root.
The building blocks
The fundamental theorem of arithmetic
Unique prime factorization
Two factor trees for 360
Testing one number
Trial division
To decide whether is prime, try to divide it. Handle the small cases first, then test divisors one by one. The moment one divides evenly, is composite. The trick that makes it fast is where you stop: at , not at .
The primality test
def is_prime(n): if n < 2: return False if n == 2: return True if n % 2 == 0: return False i = 3 while i * i <= n: # the square root is where you stop if n % i == 0: return False i += 2 # odd divisors only return Trueprint([k for k in range(30) if is_prime(k)])# [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]print(is_prime(37), is_prime(91), is_prime(2), is_prime(1))# True False True FalseThe key insight
Why checking up to √n is enough
One factor is always small
Divisor pairs of 36 mirror around √36 = 6
| Small factor () | Partner () | Product |
|---|---|---|
| 1 | 36 | 36 |
| 2 | 18 | 36 |
| 3 | 12 | 36 |
| 4 | 9 | 36 |
| 6 | 6 | 36 |
What it saves
All primes at once
The Sieve of Eratosthenes
To find every prime up to , testing each number separately costs . The sieve, described by Eratosthenes of Cyrene around 240 BC, flips the question: instead of asking "is prime?" it crosses out everything that is a multiple of a prime. Whatever is never crossed is prime.
- 1ListWrite 2 to n, all marked prime
- 2Cross multiplesFrom p squared, step by p
- 3Next uncrossedThe next survivor is prime
- 4Primes remainStop once p squared passes n
Up to 30: cross the multiples of 2, 3 and 5, then stop, because 7 × 7 = 49 > 30. Left: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29.
The sieve loop
def sieve(n): is_prime = [True] * (n + 1) is_prime[0] = is_prime[1] = False p = 2 while p * p <= n: if is_prime[p]: for m in range(p * p, n + 1, p): # start at p squared is_prime[m] = False p += 1 return [k for k in range(n + 1) if is_prime[k]]print(sieve(30)) # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]print(len(sieve(1000))) # 168Under the hood
Why start at p², and what the sieve costs
When the sieve reaches prime , the multiples each have a prime factor smaller than , so they were crossed already. The first multiple that can still be standing is . That is also why the outer loop can stop at : a prime above has and nothing left to cross.
Counting the crossings
| Crossings (about) | ||
|---|---|---|
| 1,000 | 1.9 | 1,411 |
| 1,000,000 | 2.6 | 2.1 million |
| 10,000,000 | 2.8 | 22.9 million |
Breaking numbers down
Prime factorization
Factor by smallest divisor first
Trying the smallest divisor first guarantees every factor you record is prime: a composite divisor such as 4 can never divide first, because its prime factor 2 would have been divided out already. The loop stops at of the shrinking value, and anything above 1 that remains must be a single prime larger than that.
Divisors from exponents
def factorize(n): result = [] p = 2 while p * p <= n: if n % p == 0: e = 0 while n % p == 0: n //= p e += 1 result.append((p, e)) p += 1 if n > 1: result.append((n, 1)) # leftover prime above the square root return resultprint(factorize(360)) # [(2, 3), (3, 2), (5, 1)]print(factorize(84)) # [(2, 2), (3, 1), (7, 1)]print(factorize(97)) # [(97, 1)]How many are there
Primes thin out, but never run out
The prime number theorem
| Share prime | |||
|---|---|---|---|
| 10 | 4 | 4.3 | 40% |
| 100 | 25 | 21.7 | 25% |
| 1,000 | 168 | 144.8 | 16.8% |
| 10,000 | 1,229 | 1,085.7 | 12.3% |
| 1,000,000 | 78,498 | 72,382 | 7.8% |
Choosing
Which method when
Pick the prime tool
| Task | Method | Time | Space |
|---|---|---|---|
| Is prime? | Trial division to | ||
| All primes | Sieve of Eratosthenes | ||
| Factor one | Divide by smallest prime first | ||
| Factor many | Smallest-prime-factor sieve | each | |
| Is a 300-digit prime? | Miller-Rabin |
Why it matters
Where primes show up
RSA cryptography
Multiplying two huge primes is easy; recovering and from is believed to be infeasible. HTTPS, SSH and code signing rely on that gap.
Hash table sizes
With
key % size, keys 5, 15, 25 all land in slot 5 of a size-10 table but in slots 5, 4, 3 of a size-11 table. A prime size breaks up patterns in the keys.Random number generators
Linear congruential generators ; the Lehmer form uses a prime modulus such as to get a long period.
Hashing in general
Rolling hashes (Rabin-Karp) and polynomial string hashes work modulo a large prime so collisions stay rare and arithmetic forms a field.
Problems to practise
| Problem | Idea |
|---|---|
| Count Primes (LeetCode 204) | Sieve, count primes strictly below n |
| Ugly Number (263) | Divide out 2, 3 and 5; is 1 left? |
| Ugly Number II (264) | Generate numbers whose only prime factors are 2, 3, 5 |
| Prime Palindrome (866) | Primality test plus palindrome generation |
| Closest Prime Numbers in Range (2523) | Sieve up to right, scan adjacent primes |
| Largest Component Size by Common Factor (952) | Factorize, union numbers sharing a prime |
Watch out
Pitfalls and edge cases
Do
- Return False for ; treat 2 as prime.
- Loop
while i * i <= nor tomath.isqrt(n) + 1. - Start the sieve's inner loop at
p * p. - Append the leftover
n > 1after factoring.
Don't
- Call 1 prime or forget that 2 is.
- Check divisors all the way to : for nothing.
- Run trial division on every number in a big range.
- Use trial division on 20-digit numbers; switch to Miller-Rabin.
Recap
Key takeaways
Key points
- A prime is greater than 1 with exactly two divisors; 1 is not prime and 2 is the only even prime.
- If , one factor is at most , so trial division stops at : .
- The Sieve of Eratosthenes crosses out multiples from and finds all primes up to in .
- Every has exactly one prime factorization; the exponents give divisor counts, GCD and LCM.
- When factoring, a leftover above 1 after the loop is itself prime.
- : primes thin out but never stop.
- One number: trial division. Many numbers: sieve once. Huge numbers: Miller-Rabin.