AlgoViz

Prime numbers

easy 15 min

A 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

0:00 / 5:06

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.

Step 1 of 3

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

p is prime  ⟺  p>1  and its only divisors are 1 and pp \text{ is prime} \iff p > 1 \ \text{ and its only divisors are } 1 \text{ and } p
The first ten primes are 2,3,5,7,11,13,17,19,23,292, 3, 5, 7, 11, 13, 17, 19, 23, 29. 91=7×1391 = 7 \times 13 looks prime but is composite.
  • 1 is not prime

    It has only one divisor. Calling it prime would also break unique factorization: 6=2×3=1×2×36 = 2 \times 3 = 1 \times 2 \times 3.

  • 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

    12=22×312 = 2^2 \times 3, 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

n=p1a1 p2a2⋯pkake.g.360=23×32×5,84=22×3×7n = p_1^{a_1}\, p_2^{a_2} \cdots p_k^{a_k} \qquad\text{e.g.}\qquad 360 = 2^3 \times 3^2 \times 5,\quad 84 = 2^2 \times 3 \times 7
Every integer n≥2n \ge 2 is a product of primes in exactly one way, apart from the order of the factors.

Two factor trees for 360

Split 360 by its smallest prime each time, or as 36 × 10 first. The trees differ, but both end in three 2s, two 3s and one 5.

Testing one number

Trial division

To decide whether nn is prime, try to divide it. Handle the small cases first, then test divisors one by one. The moment one divides evenly, nn is composite. The trick that makes it fast is where you stop: at n\sqrt n, not at nn.

The primality test

Is 37 prime? Check 2, then 3 and 5. Next would be 7, but 7 × 7 = 49 > 37, so 37 is prime after three checks.
Python
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 False
O(√n) trial division with the 2 special case and odd steps.
Edit and run it in your browser

The key insight

Why checking up to √n is enough

One factor is always small

n=a×b,  a>n, b>n  ⇒  a×b>n×n=n(impossible)n = a \times b,\ \ a > \sqrt n,\ b > \sqrt n \;\Rightarrow\; a \times b > \sqrt n \times \sqrt n = n \quad\text{(impossible)}
So in every factor pair at least one factor is at most n\sqrt n. If none of the numbers up to n\sqrt n divides nn, nothing above it can either.

Divisor pairs of 36 mirror around √36 = 6

Small factor (≤6\le 6)Partner (≥6\ge 6)Product
13636
21836
31236
4936
6636
Every divisor above 6 is found through its smaller partner, so the search can stop at 6.

What it saves

n=1012:1012⏟up to n checksvs1012=106⏟up to n checks (≈5×105 odd ones)n = 10^{12}: \quad \underbrace{10^{12}}_{\text{up to } n} \ \text{checks} \quad\text{vs}\quad \underbrace{\sqrt{10^{12}} = 10^{6}}_{\text{up to } \sqrt n} \ \text{checks} \ (\approx 5 \times 10^5 \text{ odd ones})
Trial division drops from O(n)O(n) to O(n)O(\sqrt n). Skipping even divisors halves it again.

All primes at once

The Sieve of Eratosthenes

To find every prime up to nn, testing each number separately costs O(nn)O(n\sqrt n). The sieve, described by Eratosthenes of Cyrene around 240 BC, flips the question: instead of asking "is kk prime?" it crosses out everything that is a multiple of a prime. Whatever is never crossed is prime.

The sieve in four moves
  1. 1ListWrite 2 to n, all marked prime
  2. 2Cross multiplesFrom p squared, step by p
  3. 3Next uncrossedThe next survivor is prime
  4. 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

For n = 49 the primes 2, 3, 5 and 7 cross out 23, 7, 2 and 1 new numbers, and 15 primes remain.
Python
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)))  # 168
The classic sieve. Build once, then every lookup is O(1).
Edit and run it in your browser

Under the hood

Why start at p², and what the sieve costs

When the sieve reaches prime pp, the multiples 2p,3p,…,(p−1)p2p, 3p, \dots, (p-1)p each have a prime factor smaller than pp, so they were crossed already. The first multiple that can still be standing is p×pp \times p. That is also why the outer loop can stop at n\sqrt n: a prime above n\sqrt n has p2>np^2 > n and nothing left to cross.

Counting the crossings

∑p≤nnp  =  n(12+13+15+17+⋯ )  ≈  nln⁡ln⁡n⇒O(nlog⁡log⁡n)\sum_{p \le \sqrt n} \frac{n}{p} \;=\; n \left(\tfrac12 + \tfrac13 + \tfrac15 + \tfrac17 + \cdots\right) \;\approx\; n \ln \ln n \quad\Rightarrow\quad O(n \log \log n)
Prime pp crosses about n/pn / p cells, and the sum of reciprocals of the primes grows like ln⁡ln⁡n\ln \ln n (Mertens). For n=106n = 10^6 that is about 2.1 million crossings, close to linear.
nnln⁡ln⁡n\ln \ln nCrossings (about)
1,0001.91,411
1,000,0002.62.1 million
10,000,0002.822.9 million
ln⁡ln⁡n\ln \ln n barely moves, which is why the sieve behaves almost like O(n)O(n). Memory is O(n)O(n) for the boolean array.

Breaking numbers down

Prime factorization

Factor by smallest divisor first

360 → divide by 2 three times → 45 → divide by 3 twice → 5. Then 4 × 4 = 16 > 5, so the leftover 5 is added: [2, 2, 2, 3, 3, 5].

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 n\sqrt n of the shrinking value, and anything above 1 that remains must be a single prime larger than that.

Divisors from exponents

n=p1a1⋯pkak  ⇒  d(n)=(a1+1)(a2+1)⋯(ak+1),d(360)=4×3×2=24n = p_1^{a_1} \cdots p_k^{a_k} \;\Rightarrow\; d(n) = (a_1 + 1)(a_2 + 1)\cdots(a_k + 1), \qquad d(360) = 4 \times 3 \times 2 = 24
Each divisor picks an exponent from 0 to aia_i for every prime. GCD takes the smaller exponent of each prime, LCM the larger.
Python
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)]
Factorization in O(√n), returning (prime, exponent) pairs.
Edit and run it in your browser

How many are there

Primes thin out, but never run out

The prime number theorem

π(n)≈nln⁡nso near n about 1 number in ln⁡n is prime\pi(n) \approx \frac{n}{\ln n} \qquad\text{so near } n \text{ about } 1 \text{ number in } \ln n \text{ is prime}
π(n)\pi(n) counts the primes up to nn. The ratio π(n)/nln⁡n\pi(n) \big/ \tfrac{n}{\ln n} tends to 1 as nn grows.
nnπ(n)\pi(n)n/ln⁡nn / \ln nShare prime
1044.340%
1002521.725%
1,000168144.816.8%
10,0001,2291,085.712.3%
1,000,00078,49872,3827.8%
The estimate runs a little low but tracks the true count. A sieve up to a million stores about 78,000 primes.

Choosing

Which method when

Pick the prime tool

Single check: trial division. Many checks or all primes: precompute with a sieve.
TaskMethodTimeSpace
Is nn prime?Trial division to n\sqrt nO(n)O(\sqrt n)O(1)O(1)
All primes ≤n\le nSieve of EratosthenesO(nlog⁡log⁡n)O(n \log \log n)O(n)O(n)
Factor one nnDivide by smallest prime firstO(n)O(\sqrt n)O(log⁡n)O(\log n)
Factor many k≤nk \le nSmallest-prime-factor sieveO(log⁡k)O(\log k) eachO(n)O(n)
Is a 300-digit nn prime?Miller-RabinO(klog⁡3n)O(k \log^3 n)O(1)O(1)

Why it matters

Where primes show up

  • RSA cryptography

    Multiplying two huge primes n=p×qn = p \times q is easy; recovering pp and qq from nn 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 xn+1=(axn+c) mod mx_{n+1} = (a x_n + c) \bmod m; the Lehmer form uses a prime modulus such as 231−12^{31} - 1 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

ProblemIdea
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 n<2n < 2; treat 2 as prime.
  • Loop while i * i <= n or to math.isqrt(n) + 1.
  • Start the sieve's inner loop at p * p.
  • Append the leftover n > 1 after factoring.

Don't

  • Call 1 prime or forget that 2 is.
  • Check divisors all the way to nn: O(n)O(n) 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 n=a×bn = a \times b, one factor is at most n\sqrt n, so trial division stops at n\sqrt n: O(n)O(\sqrt n).
  • The Sieve of Eratosthenes crosses out multiples from p2p^2 and finds all primes up to nn in O(nlog⁡log⁡n)O(n \log \log n).
  • Every n≥2n \ge 2 has exactly one prime factorization; the exponents give divisor counts, GCD and LCM.
  • When factoring, a leftover above 1 after the n\sqrt n loop is itself prime.
  • π(n)≈n/ln⁡n\pi(n) \approx n / \ln n: primes thin out but never stop.
  • One number: trial division. Many numbers: sieve once. Huge numbers: Miller-Rabin.

Sources