【LeetCode】204. Count Primes 解题小结

 题目:

Description:

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

这个题目有提示,计算素数的方法应该不用多说。

class Solution {
public:
    int countPrimes(int n) {
        vector<bool> isPrime;
        for (int i = 0; i < n; ++i){
            isPrime.push_back(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 cnt = 0;
        for (int i = 2; i < n; ++i){
            if (isPrime[i]) cnt++;
        }
        return cnt;
    }
};

 

posted on 2016-09-11 10:00  医生工程师  阅读(103)  评论(0编辑  收藏  举报

导航