LeetCode 204. Count Primes

Description:

Count the number of prime numbers less than a non-negative number, n.


This is to implement the famous: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes algorithm.

    int countPrimes(int n) {
        if(n <= 2) return 0;
        vector<bool> primes(n, true);
        for(int i = 2; i < n; ++i) {
            if(primes[i]) {
                int j = i;
                for(j = i; j + i < n; j = j + i) {
                    primes[j + i] = false;
                }
            }
        }
        int count = 0;
        for(int i = 2; i < n; ++i) {
            if(primes[i]) count++;
        }
        return count;
    }

你可能感兴趣的:(LeetCode 204. Count Primes)