letecode [204] - Count Primes

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

Example:

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

Subject to the effect :

  Seeking the number of all non-negative integer smaller than the prime number n.

Understanding:

   The most direct way is to ask whether there is the number i of each factor i-1 to 2 between. The number of statistical quality. However, this method of time complexity is too high, would exceed the time limit.

  All numbers aprotic contains prime factors, each find a prime number variation into the vessel, it is determined a number of i is determined when a prime number elements in the container whether it is a factor, did not find the number of prime numbers is also added to the vessel, but the time and space complexity is relatively high.

  Read other people's methods, Eladuosai sieve method, not all elements are set to visit the state, visit a state for the true element, it multiples are set to false. Finally obtained proton is the element to true.

Code C ++:

class Solution {
public:
    int countPrimes(int n) {
        vector<bool> visited(n,true);
        int count = 0;
        for(int i=2;i<=sqrt(n);++i){
            if(visited[i]==true){
                for(int j=2;i*j<n;++j){
                    visited[i*j] = false;
                }
            }
        }
        for(int i=2;i<n;++i){
            if(visited[i]==true)
                count++;
        }
        return count;
    }
};

operation result:

     When execution: 100 ms, beat the 32.49% of all users to submit in C ++

  Memory consumption: 8.5 MB, defeated 76.65% of all users to submit in C ++

Guess you like

Origin www.cnblogs.com/lpomeloz/p/11015034.html
Recommended