Skip to contentKEEP THE CRAFTTHE SANCTUARY

Sieve of Eratosthenes

Answer primality for every integer through an inclusive bound by crossing off multiples. Understand why crossing starts at p squared, why base primes stop at the square root, and what the Python Boolean table costs.

1 practice exercise1 interview problem

Recognize it when Many primality queries share a manageable upper bound.

Checking your account…

Sieve of Eratosthenes Code Labs

Mark Multiples from Each Prime

The sieve stores primality for every integer through a limit. When an unmarked base is reached, it is prime and its composite multiples can be crossed off.

Start Crossing Off at Prime Squared

Multiples below p squared already have a smaller prime factor and were marked earlier. Starting at p squared avoids redundant work without missing composites.

Trace Sieve Marking

Reference
def sieve_trace(limit):
    is_prime=[True]*(limit+1)
    if limit>=0:is_prime[0]=False
    if limit>=1:is_prime[1]=False
    trace=[];prime=2
    while prime*prime<=limit:
        if is_prime[prime]:
            marked=[]
            for multiple in range(prime*prime,limit+1,prime):
                if is_prime[multiple]:marked.append(multiple)
                is_prime[multiple]=False
            trace.append([prime,marked])
        prime+=1
    return trace
Practice

Implement sieve_trace(limit). Return [prime,marked_multiples] for each base prime through sqrt(limit). limit is a nonnegative integer and the upper bound is inclusive. marked_multiples contains only newly marked composites for that base, not every visited multiple.

Public tests

  • Begin marking at prime squared

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Sieve Marking

def sieve_trace(limit):
    is_prime=[True]*(limit+1)
    if limit>=0:is_prime[0]=False
    if limit>=1:is_prime[1]=False
    trace=[];prime=2
    while prime*prime<=limit:
        if is_prime[prime]:
            marked=[]
            for multiple in range(prime*prime,limit+1,prime):
                if is_prime[multiple]:marked.append(multiple)
                is_prime[multiple]=False
            trace.append([prime,marked])
        prime+=1
    return trace

Separate First Marks from Repeated Visits

The existing sieve trace reports newly marked composites for each base. Predict limit 12 carefully: the loop for base 3 visits both 9 and 12, but the trace includes only 9.

Step Executed statement State Why
Allocate and exclude is_prime=[True]*(limit+1); is_prime[0]=False; is_prime[1]=False 13 entries, then indices 0 and 1 become False Index 12 exists because the bound is inclusive.
Base 2 if is_prime[multiple]:marked.append(multiple) after base-2 loop: new marks=[4, 6, 8, 10, 12] Every visited value has factor 2; the prime 2 itself stays available.
Clear visited multiples is_prime[multiple]=False after base-2 loop: 4,6,8,10,12 are False This independent assignment occurs for every visited multiple after the optional first-mark record.
Base 3 if is_prime[multiple]:marked.append(multiple) 9 appended; 12 omitted from marked 12 is visited again but was already crossed off by base 2. The trace records first marks.
Stop while prime*prime<=limit prime=4, 16 > 12 A composite through 12 cannot require a smallest prime factor of 4 or more.
Print Output
print(sieve_trace(12)) [[2, [4, 6, 8, 10, 12]], [3, [9]]]

Read a trace row as evidence of newly ruled-out candidates. The second Lab collects the survivors instead. A full sieve is a useful shared table for many queries, whereas a single primality query may not justify this allocation.

Stop Base Primes at the Square Root

Every composite n has a factor no greater than square root n. Once p squared exceeds the limit, every remaining unmarked number is prime.

List Primes through a Limit

Reference
def primes_through(limit):
    if limit<2:return []
    is_prime=[True]*(limit+1);is_prime[0]=is_prime[1]=False
    prime=2
    while prime*prime<=limit:
        if is_prime[prime]:
            for multiple in range(prime*prime,limit+1,prime):is_prime[multiple]=False
        prime+=1
    return [value for value in range(2,limit+1) if is_prime[value]]
Practice

Implement primes_through(limit). Return every prime less than or equal to limit. limit is a nonnegative integer and the upper bound is inclusive.

Public tests

  • Keep unmarked values at least two

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

List Primes through a Limit

def primes_through(limit):
    if limit<2:return []
    is_prime=[True]*(limit+1);is_prime[0]=is_prime[1]=False
    prime=2
    while prime*prime<=limit:
        if is_prime[prime]:
            for multiple in range(prime*prime,limit+1,prime):is_prime[multiple]=False
        prime+=1
    return [value for value in range(2,limit+1) if is_prime[value]]

Choose a Full or Segmented Sieve

Use a full sieve for repeated prime queries through a manageable limit at O(n log log n) time and O(n) space. Use a segmented sieve for a large interval when storing every earlier Boolean is impractical.

Explain It in an Interview

Say: “An unmarked p is prime; I start at p squared because smaller multiples already have smaller factors. Base primes stop at the square root.” Handle zero, one, inclusive limit, and memory explicitly.

Python Version Note

Python 3.11+

The code uses standard Python syntax and containers supported by the browser Judge. The Sieve of Eratosthenes proof does not depend on a minor Python release.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Full sieve through nO(n log log n)O(n log log n)Repeated marking occurs only for prime bases; output collection also scans the table.

Space

O(n) flags and at most O(n) output or trace entries.

Assumptions

  • A Python list stores references to Boolean objects; it is not a packed one-bit-per-number bitmap.
  • The trace Lab records a composite only when first marked, even when later loops visit it again.

Invariants Worth Saying Aloud

  1. A False entry has been proved nonprime; 0 and 1 are nonprime by definition.
  2. Before processing p, composites with a prime factor smaller than p are already marked.
  3. A composite through n has a factor no greater than sqrt(n), so all surviving entries are prime after that frontier.

When To Use Or Avoid Sieve of Eratosthenes

Use It When

  • Precompute all primes or primality flags through a nonnegative integer limit.
  • Trade O(n) table storage for fast repeated membership queries.

Choose Another Tool When

  • For one very large candidate, trial division or a suitable primality test can avoid allocating every earlier entry.
  • For a narrow interval far from zero, consider a segmented sieve with base primes through the square root.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Leaving 1 in the candidate set

Only clearing index 0 leaves 1 classified as prime. Primality requires an integer greater than one.

Prevent it: Exclude both 0 and 1 before collecting surviving entries.

Avoid

flags[0] = False

Use instead

flags[0] = flags[1] = False

Crossing off the base prime itself

Starting the multiple loop at p marks p as composite. Starting at p squared retains the base and skips work already handled by smaller primes.

Prevent it: Use range(p*p, limit+1, p) after confirming p is still prime.

Avoid

for multiple in range(p, limit + 1, p):
    flags[multiple] = False

Use instead

for multiple in range(p * p, limit + 1, p):
    flags[multiple] = False

Missing a composite exactly at the limit

An exclusive stop of limit never visits 9 when p is 3 and the inclusive limit is 9.

Prevent it: The table contains index limit, so the range must stop at limit + 1.

Avoid

for multiple in range(p * p, limit, p):
    flags[multiple] = False

Use instead

for multiple in range(p * p, limit + 1, p):
    flags[multiple] = False

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.