Algorithms

Sieve of Eratosthenes

Find every prime up to a limit by repeatedly marking multiples of the next unmarked number. A classic number-theory animation.

4 minLevel 1/3The interactive stage stays ad-free.
Unmarked119Current prime—Step0 / 4
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120

Each step picks the next unmarked number as prime and crosses out its multiples. Grey cells are composite; green cells are prime. When the animation stops, all primes up to 120 remain.

What you are seeing

1

Start at 2. The first unmarked number is prime.

2

Mark every multiple of that prime as composite.

3

Move to the next unmarked number and repeat until you reach the square root of the limit.

Why it matters

Prime sieves are used in cryptography, number theory, and competitive programming. The same idea appears in modern segmented and linear sieves.

Complexity & details

Time: O(n log log n). Space: O(n).

Frequently asked questions

Why stop at the square root?+

Every composite number up to n has a prime factor no larger than √n. Larger factors are already covered by smaller ones.

What is the difference from trial division?+

Trial division tests each number separately. The sieve marks many composites at once and is much faster for ranges.