Count Primes

Count Primes

Find the number of prime numbers less than N, where N >= 0.

Sieve of Eratosthenes

class Solution {
public:
    int countPrimes(int n) {
        if (n == 0) return 0;
        
        vector<bool> isPrime(n, true);
        isPrime[0] = isPrime[1] = false;
        for(int i=2;i<sqrt(n);++i) {
            if (isPrime[i]) {
                // Start from i*i to avoid redundant marking
                for(int j=i*i;j<n;j+=i) {
                    isPrime[j] = false;
                }
            }
        }
        return count(isPrime.begin(), isPrime.end(), true);
    }
};

#math