> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Count Primes Python Solution with Tests

> Tested Python solution for LeetCode 204 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 204, [Medium](/catalog/medium). Topics: [Array](/catalog/topics/array), [Math](/catalog/topics/math), [Enumeration](/catalog/topics/enumeration), [Number Theory](/catalog/topics/number-theory), Primality Test, Sieve Theory, Prime Number Sieve. [View on LeetCode](https://leetcode.com/problems/count-primes/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 204   # by problem number
lcpy gen -s count_primes   # by problem name
```

## Problem

Given an integer `n`, return *the number of prime numbers that are strictly less than* `n`.

### Examples

```
Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
```

```
Input: n = 0
Output: 0
```

```
Input: n = 1
Output: 0
```

### Constraints

* 0 \<= n \<= 5 \* 10\<sup>6\</sup>

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/count_primes/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/count_primes/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n log log n)
    # Space: O(n)
    def count_primes(self, n: int) -> int:
        if n < 3:
            return 0
        is_prime = [True] * n
        is_prime[0] = is_prime[1] = False
        for i in range(2, int(n**0.5) + 1):
            if is_prime[i]:
                for multiple in range(i * i, n, i):
                    is_prime[multiple] = False
        return sum(is_prime)
```

## Complexity

| Time | Space |
| - | - |
| O(n log log n) | O(n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.