V

Algorithm Visualizer

ZHEN
Share on WeiboShare on XGitHub repositoryAuthor website
Learning ToolsAlgorithm Complexity ReferenceAlgorithm Learning Paths
Data StructuresArrayLinked ListStackQueue and DequeBinary Search TreeBinary HeapHash TableGraphTrieDisjoint Set UnionLRU CacheSkip ListSegment TreeB+ TreeBloom FilterFenwick Tree
SortingBubble SortCocktail Shaker SortBitonic SortSelection SortInsertion SortBinary Insertion SortShell SortMerge SortTop-Down Merge SortQuick SortThree-Way Quick SortDual-Pivot Quick SortHeap SortCounting SortRadix SortBucket Sort
Graph AlgorithmsDijkstra's Shortest PathKruskal's Minimum Spanning TreePrim's Minimum Spanning TreeBellman-Ford Shortest PathsTopological SortFloyd-WarshallStrongly Connected Components2-SATMaximum FlowBipartite MatchingLowest Common AncestorEulerian Path
Dynamic ProgrammingEdit Distance0/1 KnapsackUnbounded KnapsackLongest Common SubsequenceLongest Increasing SubsequenceCoin ChangeStone MergingTraveling Salesperson DPTree Dynamic ProgrammingDigit DPRerooting DP
Backtracking and SearchN-QueensSubsetsPermutationsCombination SumMaze Solving with DFSNumber of IslandsWord SearchSudoku SolverA* Search
StringsKMP String MatchingRabin-Karp String MatchingBoyer-Moore String MatchingManacher's Longest Palindromic SubstringSuffix ArrayLCP ArrayAho-Corasick AutomatonZ Function
Math and Number TheorySieve of EratosthenesLinear SieveEuclidean AlgorithmBinary ExponentiationExtended Euclidean AlgorithmChinese Remainder TheoremEuler's Totient FunctionMiller-Rabin Primality TestFast Fourier TransformPollard's Rho Factorization
Computational GeometryConvex HullRotating CalipersClosest Pair of PointsLine Segment IntersectionBentley-Ottmann Sweep Line
SearchingBinary SearchLower and Upper BoundSearch in a Rotated Sorted ArrayBinary Search on the AnswerTernary Search

Sieve of Eratosthenes

Mark composite multiples to reveal every prime up to N

Find primes in one shared pass

Begin with every integer from 2 through N unmarked. The next unmarked value is prime. Mark all of its multiples as composite, then continue to the next unmarked value. The values never marked are exactly the primes.

Start at p squared

Multiples smaller than p^2 already contain a smaller prime factor and were marked earlier. Once p^2 > N, every composite at most N has already been reached through a factor at most sqrt(N), so all remaining unmarked values can be confirmed together.

The number grid runs to 30. Green cells are confirmed primes, gray cells are composite, amber marks the current prime, and newly crossed-out multiples flash red.

1
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

Lay out 1 through 30; 1 is neither prime nor composite, and all larger values start unmarked.

1function sieve(n: number): number[] {
2 const isComposite = new Array(n + 1).fill(false); // initially unmarked
3 const primes: number[] = [];
4 for (let p = 2; p <= n; p++) {
5 if (!isComposite[p]) { // unmarked p is prime
6 primes.push(p);
7 for (let m = p * p; m <= n; m += p) // mark multiples of p from p^2
8 isComposite[m] = true;
9 }
10 }
11 return primes; // remaining unmarked values are prime
12}
Range1..30
Confirmed primes0
1 / 9

Near-linear preprocessing

The harmonic sum over prime multiples gives O(N log log N) time and the marking array uses O(N) space. The sieve is ideal when many later queries need the same bounded prime table.

Invariant: before processing prime p, every composite below p^2 has already been marked by a smaller prime factor.

Continue the number-theory path with the remainder invariant in the Euclidean Algorithm.