LeetCode 204. Count Primes

暴力的话,判断n是否是prime的时候只要循环到根号n,会超时。

另一种解法利用 埃拉托斯特尼筛法Sieve of Eratosthenes ,可以详见 http://www.cnblogs.com/grandyang/p/4462810.html 中的图。

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

        int cnt=0;
        for (int i=2;i<n;++i)
            if (a[i]) ++cnt;
        return cnt;
    }
};

 

posted @ 2018-08-20 05:24  約束の空  阅读(78)  评论(0)    收藏  举报