[Simple Algorithm] 41. Counting Prime Numbers

topic:

Count the number of all prime numbers less than the non-negative integer n.

Example:

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

Problem solving ideas:

 

Code:

class Solution {
public:
    bool isPrime(int num) {
        if (num <= 1) return false;
        for (int i = 2; i*i <= num; ++i) {
            if (num%i == 0) return false;
        }
        return true;
    }

    int countPrimes(int n) {
        bool *isPrime = new bool[n];
        for (int i = 2; i < n; ++i) {
            isPrime[i] = true;
        }
        for (int i = 2; i*i < n; ++i) {
            if (!isPrime[i]) continue;
            for (int j = i*i; j < n; j += i) {
                isPrime[j] = false;
            }
        }
        int count = 0;
        for (int i = 2; i < n; ++i) {
            if (isPrime[i]) count++;
        }
        return count;
    }
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325442340&siteId=291194637