Article start
DSA Course: Interview Patterns and Problem Solving
Module 15: Math & Number Theory

Sieve of Eratosthenes: Prime Marking Pattern

Generate all primes up to n by marking composite multiples.

May 29, 2026·27

Learning Outcome

After this lesson, you should be able to mark composites once from p squared and collect primes efficiently.

Problem Statement

Given n, return all prime numbers less than or equal to n.

InputOutputWhy
n = 10[2,3,5,7]2, 3, 5, and 7 are the primes up to 10.

Brute Force Approach

Run a separate prime check for every number from 2 to n. This repeats factor checks across many numbers.

Optimized Approach

Keep a boolean table. When p is still marked prime, mark p p, p p + p, and later multiples as composite.

Exact Pseudocode

if n < 2:
  return []
isPrime[0..n] = true
isPrime[0] = false
isPrime[1] = false
for p from 2 while p * p <= n:
  if isPrime[p]:
    for multiple from p * p to n step p:
      isPrime[multiple] = false
return all indexes still marked true

Reference Code

class Solution:
    def primesUpTo(self, n):
        if n < 2:
            return []

        is_prime = [True] * (n + 1)
        is_prime[0] = False
        is_prime[1] = False

        p = 2
        while p * p <= n:
            if is_prime[p]:
                for multiple in range(p * p, n + 1, p):
                    is_prime[multiple] = False
            p += 1

        return [i for i in range(2, n + 1) if is_prime[i]]

Sample Dry Run

StepStateResult
InitializeMark 0 and 1 as not prime2 through 10 start true
p = 2Mark 4,6,8,10even composites removed
p = 3Mark 9multiples below 9 were handled
Collect2,3,5,7 stay trueanswer ready

Complexity

MeasureValueReason
TimeO(n log log n)Each prime marks a shrinking list of multiples.
SpaceO(n)The boolean table stores primality state for 0 through n.

Edge Cases

  • n less than 2 should return an empty list.
  • Start marking at p * p to avoid repeated work.
  • Use a wide integer for p * p when n can be large.

Interview Checklist

  • Initialize 0 and 1 as not prime.
  • Only mark multiples when p is still prime.
  • Collect indexes that remain true.

FAQs

Why start marking at p squared?

Smaller multiples of p already have a smaller prime factor and were marked earlier.

When should the outer loop stop?

Once p squared is greater than n, remaining unmarked numbers are prime.

What is the core pattern?

Prime marking table.

Test your knowledge

Take a quick quiz based on this chapter.

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.