SDE & MLE Prep

204. Count Primes

Problem

Return how many prime numbers are strictly less than n.

Example: 10 → 4 (2, 3, 5, 7)

Constraints: n ≤ 5·10⁶.

Sieve of Eratosthenes: for each prime p with p² < n, cross out p², p²+p, ….

Complexity: O(n log log n).

class Solution:
    def countPrimes(self, n: int) -> int:
        if n < 3:
            return 0
        is_p = bytearray([1]) * n
        is_p[0] = is_p[1] = 0
        for p in range(2, int(n ** 0.5) + 1):
            if is_p[p]:
                is_p[p * p::p] = bytearray(len(range(p * p, n, p)))
        return sum(is_p)