Count Primes solution explained

Count Primes is solved with the Sieve of Eratosthenes: make an array of n flags, and for each p from 2 while p * p < n, if p is still unmarked, mark p * p, p * p + p, p * p + 2p and so on as composite; the unmarked numbers from 2 to n - 1 are the primes. It runs in O(n log log n) time and O(n) memory, far faster than testing each number by trial division, which costs up to O(n * sqrt(n)). Note the range is strictly below n, so n = 0, 1 and 2 all give 0.

By Published 7 min read

The problem in plain words

A prime is a whole number greater than 1 whose only divisors are 1 and itself. Given a non-negative integer n, report how many primes are smaller than n. The input can be large enough, often into the millions, that checking numbers one at a time is too slow, which is the point of the exercise. The answer is a count, so you never need to list the primes, though the sieve gives you the list for free.

Examples computed with the code on this page
nPrimes below nCount
0, 1 or 2none0
321
302, 3, 5, 7, 11, 13, 17, 19, 23, 2910
31the same ten; 31 itself is not below 3110
1002 up to 9725
1,0002 up to 997168
1,000,00078,498
Examples computed with the code on this page. Scroll sideways on a small screen.

What the interviewer is checking

Most candidates have heard of the sieve, so the interview tends to go past naming it. Expect to be asked why the inner loop starts at p squared, why the outer loop can stop at the square root of n, what the running time is and why, and how much memory it takes at the upper limit. Reading "less than n" correctly is part of the test, as is not counting 0 and 1. Some interviewers compare it with checking primality of a single number, which is a different problem with a different best answer.

Follow-ups

  • n is too big for memory. Use a segmented sieve: find the primes up to sqrt(n) with a small sieve, then cross out multiples of those primes in fixed-size windows of the range.
  • Halve the memory. Store only odd numbers, since 2 is the only even prime; index i stands for 2i + 1.
  • Is one large number prime? Trial division up to its square root is fine for moderate values; for very large values, mention probabilistic tests such as Miller-Rabin rather than a sieve.
  • Count primes in a range [a, b). Sieve up to b and count from a, or use the segmented sieve for the window.
  • Return the k-th prime. Sieve up to an estimate and extend if it falls short.

First version: trial division for every number

For each k from 2 to n - 1, try divisors d starting at 2 while d * d <= k; if any divides k, it is composite. The square-root bound works because a composite number has two factors and one of them is at most its square root. Each test costs up to sqrt(k) divisions, so counting up to n costs up to about n * sqrt(n). It is a perfect correctness reference for small n and a natural thing to say first, but it falls behind the sieve quickly as n grows.

@@count-primes/slow.py@@
Python: trial division per number. O(n * sqrt(n)) time, O(1) memory.

Expected version: the Sieve of Eratosthenes

Flip the work around. Instead of asking each number for a divisor, let each prime announce its multiples. Start with every number from 2 to n - 1 marked as a candidate. Take the smallest candidate, 2: it is prime, so mark 4, 6, 8 and so on as composite. The next candidate, 3, is prime, so mark its multiples. When you reach a number that is still a candidate, nothing smaller divided it, so it is prime. Two details make it fast. The crossing-out for p can begin at p * p, since any smaller multiple of p, such as 3p, also has a smaller prime factor and was already marked. And once p * p reaches n, no new marks can happen, so the outer loop stops there.

@@count-primes/fast.py@@
Python: sieve with slice assignment on a bytearray. O(n log log n) time, n bytes of memory.

In Python, assigning a zero-filled bytes object to the slice candidate[p * p::p] marks every multiple at C speed instead of in an interpreted loop; len(range(p * p, n, p)) gives exactly the number of positions in that slice. In JavaScript a typed array is the natural choice, and counting can happen in the same loop that finds the primes.

@@count-primes/fast.js@@
JavaScript: Uint8Array sieve, counting as it goes. O(n log log n) time, O(n) memory.

Where does n log log n come from? Prime p crosses out about n / p numbers, and the sum of 1 / p over the primes up to n grows like log log n, which is almost flat. In practice the sieve is limited by memory traffic, not arithmetic, which is why compact flag arrays help.

Cost

Counting primes below n
ApproachTimeMemoryWhen it fits
Trial division per numberO(n * sqrt(n))O(1)Small n, or as a test oracle
Sieve of EratosthenesO(n log log n)O(n)The standard answer for n up to tens of millions
Odd-only sieveO(n log log n)O(n / 2)When memory is tight
Segmented sieveO(n log log n)O(sqrt(n) + window)When n does not fit in memory
Counting primes below n. Scroll sideways on a small screen.

Edge cases

  • n = 0, 1 or 2: no primes below, and an array of size 0 or 1 must not be indexed at [1].
  • n = 3: the first non-zero answer, counting only 2.
  • n itself prime, such as 31: it must not be counted.
  • Perfect squares of primes, such as n = 50 with 49 = 7 * 7: the outer loop condition p * p < n must still let 7 mark 49.
  • The largest n allowed: check that n flags fit in memory and that p * p cannot overflow in a fixed-width language.

Common slips

  • Counting primes up to and including n, which gives 11 instead of 10 for n = 31.
  • Leaving 0 and 1 marked as candidates, which adds 2 to every answer.
  • Starting the inner loop at 2p instead of p * p. Still correct, just slower; say you know the better start.
  • Running the outer loop to n and crossing out from p * p for large p, which wastes time and, in C-family languages, can overflow p * p.
  • Using a list of Python booleans or integers instead of a bytearray, which uses several times more memory for the same flags.

Talking through it

Fictional example

Naming the sieve and defending its details
Candidate
Strictly less than n, so for n of 2 or less the answer is zero. Testing each number by trial division is n times root n, so I'll sieve instead.
Candidate
One flag per number. For each p that's still unmarked, I cross out its multiples starting at p squared, because smaller multiples already have a smaller prime factor.
Candidate
I can stop the outer loop once p squared reaches n. Time is n log log n, memory is n bytes. If n were too big for memory I'd switch to a segmented sieve.

Power of Two is another number-theory warm-up where a structural fact replaces a loop. Fizz Buzz is the gentlest divisibility question and a good place to talk about modulo costs. Fibonacci Number shares the theme of trading memory for time by storing results you would otherwise recompute.

Natively for practice

The sieve itself is short; the follow-up questions are where interviews are decided. During practice on Mac or Windows, Natively can read the problem from a screenshot, quiz you on why crossing-out starts at p squared, and suggest the segmented-sieve follow-up to rehearse. Its transcript of the mock is a quick way to check that you said "strictly less than n" before you wrote the loop.

Questions people ask

How do you count primes less than n efficiently?

Use the Sieve of Eratosthenes: keep one flag per number, and for each unmarked p with p * p < n, mark its multiples from p * p upward as composite. Count the unmarked numbers from 2 to n - 1.

Why does the sieve start crossing out at p squared?

Every smaller multiple of p, such as 2p or 3p, has a prime factor smaller than p, so it was already marked when that smaller prime was processed.

What is the time complexity of the Sieve of Eratosthenes?

O(n log log n) time and O(n) memory. Each prime p marks about n / p numbers, and the sum of 1 / p over primes up to n grows like log log n.

How many primes are there below 1,000,000?

78,498. That is the value the sieve on this page returns for n = 1,000,000, and it matches trial division on smaller ranges.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP