Problem 204

Abstract / Summary

Count how many numbers are prime up to a given limit.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0204.py

class Solution:
    def countPrimes(self, n: int) -> int:
        if n <= 2:
            return 0

        all = [True] * n

        # scan only odd numbers
        result = 1
        for i in range(3, n, 2):
            if all[i] == False:
                continue

            result += 1

            # sieve
            j = 3*i
            while j < n:
                all[j] = False
                j += 2*i

        return result
22 lines | 458 bytes | submitted August 15, 2023 | GitHub   13% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 36% (3+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Enumeration
  • Math
  • Number Theory
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a method countPrimes that returns the number of prime numbers strictly less than a given integer n. It employs a variant of the Sieve of Eratosthenes that deliberately ignores even numbers after handling the smallest prime (2). The algorithm initializes a boolean array, iterates over odd candidates, marks their odd multiples as non-prime, and accumulates a count of discovered primes.

Core Logic

Early Return for Small Input

The method begins by handling the situation where the input does not admit any prime numbers below it.

if n <= 2:
    return 0

When n is 0, 1, or 2, the function immediately returns 0 because there are no prime numbers less than 2. This guard prevents unnecessary allocation of the boolean array for trivial cases.

Boolean Array Initialization

A list named all is created to represent the primality status of each integer from 0 up to n-1. All entries are initially set to True, indicating potential primality.

all = [True] * n

The array includes indices for even numbers, but the algorithm will never consult those entries after the initial setup, allowing the same structure to be reused without extra bookkeeping.

Counting the Prime 2

Since the sieve will only process odd numbers, the count of known primes is seeded with the prime number 2.

result = 1

This pre-increment ensures that the final result includes 2 without having to treat it as part of the main loop.

Iteration Over Odd Candidates

The main loop steps through odd integers starting at 3, up to but not including n. The step size of 2 guarantees that only odd indices are examined.

for i in range(3, n, 2):
    if all[i] == False:
        continue
    result += 1
    # sieve step follows

If the current odd index i has already been marked as non-prime (False), the loop skips further work for that value. Otherwise, i is a prime, and the counter result is incremented.

Sieve of Odd Multiples

For each discovered odd prime i, the algorithm marks its odd multiples as composite. The first multiple considered is 3*i, which is the smallest odd multiple greater than i itself. The increment 2*i preserves oddness, because adding an even multiple of an odd number yields another odd number.

j = 3 * i
while j < n:
    all[j] = False
    j += 2 * i

By starting at 3*i rather than i*i, the implementation avoids marking the prime itself and also skips even multiples that would already be known as non-prime. The inner loop continues until the multiple exceeds the bound n.

Final Result

After the outer loop finishes scanning all odd candidates, the accumulated result holds the total count of primes below n.

return result

Edge Cases Handled

The early return clause covers inputs where n is less than or equal to 2, ensuring the function returns a correct count of zero without proceeding to the sieve. The loop bounds (range(3, n, 2)) naturally handle the situation where n is just above 2, such as n = 3, by producing an empty iteration and leaving the result at the initial count of 1 (the prime 2). The inner while loop’s condition j < n guarantees that attempts to mark multiples never exceed the allocated array, preventing index errors for any valid n.

Performance Optimizations

The algorithm incorporates several deliberate choices to reduce work and memory traffic:

  • Odd-only scanning: By iterating with a step of 2, the method eliminates half of the candidate numbers from consideration, effectively halving the number of loop iterations compared to a naïve full-range scan.
  • Pre-counting the prime 2: Seeding the result with 1 removes the need to treat the even prime as a special case inside the main loop, simplifying the control flow.
  • Skipping even multiples: The inner sieve starts at 3*i and increments by 2*i, which means only odd multiples are visited. Even multiples are already known to be composite, so they are never written to the boolean array, reducing unnecessary assignments.
  • Early continuation: The if all[i] == False: continue guard prevents the algorithm from performing the inner marking step for numbers that have already been identified as composite, avoiding redundant work.

These choices collectively lower the number of arithmetic operations and memory writes, yielding a faster execution profile for typical input sizes while maintaining a straightforward implementation.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long row of numbered tiles on the floor, starting from zero and going all the way up to the number that was chosen. At the start, this code pretends that every single tile is a special number called a prime.

First, the code checks if the number is very small. If the number is zero, one, or two, it knows there are no primes to find, so it just stops immediately.

For bigger numbers, the process begins by assuming everything is a prime. Since the number two is the only even prime, the code starts by counting that one right away. Then, it walks down the line looking only at the odd numbered tiles. Every time it lands on a tile that is still marked as true, that means another prime has been discovered.

Once a prime is found, the code performs a clever trick to cross off any other numbers that can be built by multiplying that prime by something else, because those are not prime. It jumps along the line, flipping those tiles to false so they do not count anymore. It keeps skipping ahead like this until it reaches the very end of the row of tiles. By the time it finishes walking through the line, it knows exactly how many primes are hiding in that group.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.54 | σ = 1.08

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python C# Java JS Go
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
FelixFan1122 C#
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
qiyuangong C++
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
FelixFan1122 C#
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
qiyuangong C++
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
49 links | 34 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Count Primes | LeetCode 204 | Google Coding Interview Tutorial'
Terrible Whiteboard 14 mins
Count Primes | LeetCode 204 | Google Coding Interview Tutorial
YouTube video 'Count Primes - LeetCode 204 - Sieve of Eratosthenes - Coding Interview'
One Code Man 5 mins
Count Primes - LeetCode 204 - Sieve of Eratosthenes - Coding Interview
YouTube video 'Sieve of Eratosthenes | Count Primes | Leetcode 204'
Nideesh Terapalli 6 mins
Sieve of Eratosthenes | Count Primes | Leetcode 204
YouTube video 'Count Primes | Leetcode 204 | Sieve of Eratosthenes | Apple Amazon Microsoft'
Naresh Gupta 11 mins
Count Primes | Leetcode 204 | Sieve of Eratosthenes | Apple Amazon Microsoft
YouTube video 'Count Primes | LeetCode 204 | Theory + Python code (Sieve of Eratosthenes explained)'
Sai Anish Malla 16 mins
Count Primes | LeetCode 204 | Theory + Python code (Sieve of Eratosthenes explained)
YouTube video 'Leetcode 204 - Count Primes (JAVA Solution Explained!)'
LC Bear 10 mins
Leetcode 204 - Count Primes (JAVA Solution Explained!)
YouTube video 'Leetcode 204: Count Primes | Bruteforce, Sieve of Eratosthenes in Telugu | Python DSA | srkcodes'
Srk Codes 22 mins
Leetcode 204: Count Primes | Bruteforce, Sieve of Eratosthenes in Telugu | Python DSA | srkcodes
YouTube video '204. Count Primes | Leetcode |  Sieve of Eratosthenes | Math based | Fundamentals'
Coding with Tamilarasan 11 mins
204. Count Primes | Leetcode | Sieve of Eratosthenes | Math based | Fundamentals
YouTube video 'Sieve of Eratosthenes | Count Primes | Leetcode 204 | Live coding session | LC Easy'
Coding Decoded 9 mins
Sieve of Eratosthenes | Count Primes | Leetcode 204 | Live coding session | LC Easy
YouTube video 'Daily Leetcode #405: May 10, 2021 - 204. Count Primes'
Programming Live with Larry 8 mins
Daily Leetcode #405: May 10, 2021 - 204. Count Primes
YouTube video 'Count Primes | Leetcode 204 | Approach + Code with explanation.'
Pirai's Academy 9 mins
Count Primes | Leetcode 204 | Approach + Code with explanation.
YouTube video 'Leetcode 204. Count Primes'
Math Geeks 3 mins
Leetcode 204. Count Primes
YouTube video 'Leetcode | 204. Count Primes | Easy | Javascript'
Software Interviews Prep 16 mins
Leetcode | 204. Count Primes | Easy | Javascript
YouTube video 'Count Primes | Leetcode 204 | Approach + Code with explanation.'
Pirai's Academy 9 mins
Count Primes | Leetcode 204 | Approach + Code with explanation.
YouTube video 'Leetcode Question 204 "Count Primes" in Python'
Ghumman Tech 12 mins
Leetcode Question 204 "Count Primes" in Python
YouTube video 'DAY 311: LeetCode Problem 204. Count Primes - Swift'
iOSxBank 9 mins
DAY 311: LeetCode Problem 204. Count Primes - Swift
YouTube video '26. LeetCode 204. Count Primes [ JAVASCRIPT ]'
Web Fusion with Bharadwaj 4 mins
26. LeetCode 204. Count Primes [ JAVASCRIPT ]
YouTube video 'LeetCode 204 | Count Primes | Array | Java'
Sleepy Cracker 4 mins
LeetCode 204 | Count Primes | Array | Java
YouTube video 'leetcode 204. Count Primes - Sieve of Eratosthenes; the basics in this playlist'
Code-Yao 11 mins
leetcode 204. Count Primes - Sieve of Eratosthenes; the basics in this playlist
19 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

4 similar problems

Solved On The Same Day

30 solutions   August 15, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality