KEVOS
ArticlesServicesCase studiesAboutContact
ArticlesServicesCase studiesAboutContact
← ArticlesThe Sieve of EratosthenesEngineering · Engineering MathematicsLesson 563/883← PrevNext →
GuidePublished 7 Aug 2026Updated 13 Aug 20268 min readBy Kevin Jogin
On this page

Ask about this page

KEVOS AIThe Sieve of Eratosthenes

KEVOS knowledge first · trusted web sources when needed

Engineering  /  Mathematics  — The Distribution of Primes

The Sieve of Eratosthenes

The classical sieve for enumerating primes, its complexity, segmented variants, and its role as a precomputation step.

Page KV-MATH-0335Reading time 4 minReviewed 2026-08-07Author Kevin Jogin

Executive summary

The sieve of Eratosthenes enumerates all primes up to a bound by repeatedly marking multiples of each prime found. It is optimal in practice for enumerating primes and is the standard precomputation for trial division tables.

Its memory requirement, not its time, is the binding constraint, which is what motivates the segmented variant.

Learning objectives

  1. State the algorithm and its time complexity.
  2. Explain the two standard optimisations.
  3. Describe the segmented variant and its memory profile.

01The algorithm

Algorithm

Sieve of Eratosthenes

Inputbound N
Outputall primes not exceeding N
  1. Create a boolean array marked[2..N], all entries initially false.
  2. For i from 2 while i² ≤ N:
  3.   If marked[i] is false, then i is prime:
  4.     For j from i² to N in steps of i, set marked[j] = true.
  5. Return every index whose entry remains false.
Cost  O(N log log N) operations, O(N) bits of memory

Two optimisations are built into the statement and both matter. Starting the inner loop at i² rather than 2i is correct because smaller multiples of i already carry a smaller prime factor and have been marked. Stopping the outer loop at √N is correct because a composite below N must have a factor below √N.

02Why log log N

The total work is the number of marking operations, which is the sum over primes p ≤ √N of N/p. By Mertens' theorem that sum is N ln ln N up to constants.

Σ_{p ≤ N} N/p = N · (ln ln N + M + o(1))
Note
The log log factor is so slowly growing that the sieve is effectively linear for any practical N. It is one of the rare cases where an asymptotic factor can safely be ignored: ln ln of a trillion is about 3.3.

03Memory and the segmented variant

Caution
Memory is the real constraint. A plain sieve to 10¹² needs a terabit of storage even with one bit per candidate, which is impractical, while the time would be entirely manageable.

The segmented sieve fixes this by processing the range in blocks that fit in cache.

  1. Sieve the base

    Find all primes up to √N with an ordinary sieve. This needs only √N bits.

  2. Process segments

    Divide [2, N] into blocks of size around √N or the cache size, whichever is smaller.

  3. Mark within a block

    For each base prime, mark its multiples inside the current block only, starting from the first multiple in range.

  4. Emit and discard

    Report the primes in the block and reuse the buffer for the next segment.

Sieve variants
VariantTimeMemoryNotes
PlainO(N log log N)O(N) bitsSimple; memory-bound beyond about 10⁹
SegmentedO(N log log N)O(√N) bitsCache-friendly; the practical choice
Wheel factorisedLower constantO(√N) bitsSkips multiples of small primes entirely
Linear (Euler)O(N)O(N)Each composite marked once; slower in practice due to memory access

The linear sieve is a curiosity worth knowing about: it achieves genuinely linear time by marking each composite exactly once, yet is usually slower than the segmented Eratosthenes sieve because its memory access pattern defeats the cache.

04Frequently asked questions

Is the sieve useful for testing a single large number?

No. Sieving to √n to test one n-bit number is exponential in the input length. The sieve is for enumerating many small primes; Miller-Rabin is for testing one large one.

What is the sieve typically used for in this subject?

Building the small-prime table used for trial division in prime generation, and constructing the factor base for index calculus and quadratic sieve factoring. Both need all primes below a moderate bound.

Why is the linear sieve slower despite better complexity?

Because it requires maintaining the smallest prime factor of each index and accesses memory in a less predictable pattern. On modern hardware the cache behaviour dominates the operation count.

Related pages

  • Trial Division and Basic Primality Testing
  • Trial Division up to a Small Bound
  • Mertens' Theorem
  • The Prime Number Theorem

Sources and method

Structural reference: Victor Shoup, A Computational Introduction to Number Theory and Algebra, Version 1, Cambridge University Press, 2005 — book pages 85-86.

This page carries the durable method layer only: definitions, constructions, algorithms, complexity results and selection criteria, authored originally for KEVOS. No text is transcribed or paraphrased from the source, and no numeric tables or benchmark data are reproduced — these are routed to live authoritative sources instead.

Author: Kevin Jogin. Last reviewed 2026-08-07.

Handbook application: from concept to controlled practice

Purpose. This expanded section turns the original page into a practical handbook. It preserves the supplied material and adds a repeatable way to apply, check and review The Sieve of Eratosthenes. It does not replace a contract, legislation, a controlled standard, competent engineering judgement or specialist advice.

The operating aim is to turn a compact mathematical statement into a usable chain of definitions, claims, examples and checks. Read the original explanation first, then use the workflow and checks below to convert knowledge into evidence.

Treat The Sieve of Eratosthenes as a network of definitions and implications, not as a list of formulas. The working vocabulary on this page—sieve, eratosthenes, segmented, classical, enumerating—should be made explicit before any proof or computation begins. Record the ambient set or structure, the permitted operations and the equality or equivalence relation in use. A compact theorem often changes meaning when the base field, finiteness condition, commutativity assumption or direction of an action changes.

For a proof, write the hypotheses as a checklist and mark the line at which each one is used. For a computation, state the representation of the input, the arithmetic model, the termination condition and the output invariant. For a classification problem, distinguish existence from uniqueness and distinguish an object from its representation. These separations prevent a correct local calculation from being mistaken for the general result.

A useful worked example should be small enough to inspect completely but rich enough to exercise the main mechanism. Compute the result in two ways where practical: symbolically and by substitution, structurally and numerically, or directly and through a normal form. Then include one near-miss example in which a hypothesis fails. The contrast explains why the theorem is shaped as it is and gives the reader a diagnostic pattern for later problems.

Verification is part of the mathematics. Check domains and codomains, substitute proposed solutions, test identity and zero cases, compare dimensions or cardinalities, and confirm that maps respect the required operations. In numerical work, report precision, conditioning and a residual rather than digits alone. In algorithmic work, separate mathematical correctness from implementation complexity and resource limits.

Step-by-step operating method

  1. Fix the setting. State the objects, ambient structure, notation and assumptions before manipulating symbols.
  2. Separate claims. Distinguish definitions, hypotheses, conclusions, equivalent conditions and consequences.
  3. Choose a method. Select proof, construction, calculation or algorithm according to the question actually asked.
  4. Work a small case. Use the smallest non-trivial example to expose the mechanism and test edge behaviour.
  5. Verify independently. Substitute back, check invariants, test boundary cases or use an alternative derivation.

Worked-example protocol

Illustrative method—not a source theorem. Start with a small admissible input and list the definitions it must satisfy. Carry out each transformation on a separate line, citing the property that permits it. Preserve exact values until approximation is necessary. At the end, verify the output against the original definition and one invariant such as dimension, degree, determinant, order, norm or residual. Then alter one hypothesis and observe which step ceases to be valid. This protocol creates a reusable example without inventing a theorem-specific numerical answer.

StageRecordQuality check
InputObjects, domain, notation, assumptionsEvery symbol is defined
MethodPermitted operation or cited result at each stepAll hypotheses hold
OutputExact result and representationCorrect type, domain and form
VerificationSubstitution, invariant or alternative derivationIndependent agreement
Boundary testZero, identity, degenerate or failed hypothesisScope is understood

Common failure modes and recovery actions

1. Watch for

Using a theorem without checking every hypothesis.

Recovery: Return to the governing definition or requirement and restate the decision in one sentence.

2. Watch for

Treating a suggestive example as a proof of the general case.

Recovery: Separate evidence from assumption, assign an owner and set a date for validation.

3. Watch for

Changing notation or conventions part-way through an argument.

Recovery: Run a small counterexample, boundary test, pilot or independent check before proceeding.

4. Watch for

Hiding a division-by-zero, convergence, finiteness or commutativity assumption.

Recovery: Record the consequence, decision and rationale, then update the controlled baseline.

5. Watch for

Reporting a computed result without a residual, substitution or structural check.

Recovery: Escalate when the issue affects safety, compliance, acceptance, material value or an agreed tolerance.

Review checklist

  • Can every symbol be traced to a definition or prior result?
  • Which hypothesis does each major step use?
  • Does the method cover zero, identity, degenerate and boundary cases?
  • Can the conclusion be checked by a second representation or calculation?
  • Are mandatory requirements distinguished from recommendations and illustrative values?
  • Are sources, assumptions, units, dates and versions recorded closely enough to reproduce the decision?
  • Have safety, legal, ethical, stakeholder and operational consequences been considered at the appropriate level?
  • Is there a named owner and a trigger for review, escalation, change or retirement?

Questions for deeper application

What is the most important distinction a practitioner must preserve when applying The Sieve of Eratosthenes?

Answer with a fact or cited source where available. Where evidence is incomplete, record the assumption, consequence, responsible owner and next validation action.

Which assumption about sieve would change the result most if it proved false?

Answer with a fact or cited source where available. Where evidence is incomplete, record the assumption, consequence, responsible owner and next validation action.

What evidence would allow an independent reviewer to reproduce or challenge the conclusion?

Answer with a fact or cited source where available. Where evidence is incomplete, record the assumption, consequence, responsible owner and next validation action.

Which boundary, exception or failure case has not yet been tested?

Answer with a fact or cited source where available. Where evidence is incomplete, record the assumption, consequence, responsible owner and next validation action.

What must be handed over, monitored or reviewed after the immediate work is complete?

Answer with a fact or cited source where available. Where evidence is incomplete, record the assumption, consequence, responsible owner and next validation action.

Authoritative references and use notes

The sources below were selected as institutional or primary guidance for the broader practice. They support the handbook method; they do not imply that every statement or clause in a source applies to every project. Confirm the current edition, jurisdiction, contract and application before treating any requirement as mandatory.

  • MIT OpenCourseWare — Number Theory I — Massachusetts Institute of Technology. Used for algebraic and analytic number theory. Accessed 2026-08-13.
  • MIT OpenCourseWare — Algebra I — Massachusetts Institute of Technology. Used for groups, vector spaces, linear transformations and linear groups. Accessed 2026-08-13.

Continue learning

Mertens' TheoremGuide · Engineering MathematicsNEXT LESSON →The Prime Number TheoremGuide · Engineering MathematicsBertrand's PostulateGuide · Engineering MathematicsThe Error Term in the Prime Number TheoremGuide · Engineering Mathematics
KEVOS · Engineering, manufacturing and project improvement
ArticlesServicesCase studiesAboutContact
© 2026 KEVOS®