C++, Euler sieve, O(N), Easy


  • -1
    X
    class Solution {
    public:
        int countPrimes(int n) {
        //true for prime
        vector<bool>check_for_prime(n,true);
        //record founded prime
        vector<int>primes;
        for(int i = 2;i<n;i++){
            if(check_for_prime[i]) {
             primes.push_back(i);
            }
           //get composite numbers using its minimum prime factor
            for(int j = 0;j<primes.size();j++){
                //check if out of range
                if(primes[j]*i>=n) break;
                check_for_prime[primes[j]*i] = false;
                //if so, primes[j+1] will not be the minimum prime factor for (prime[j+1]*i) 
                if(i%primes[j] == 0) break;
            }
        }
        return primes.size();
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.