leecode第二百零四题(计数质数)

class Solution {
public:
    int countPrimes(int n) {
        if(n==0)
            return 0;
        int index=1;
        vector<bool> is_zhishu(n,true);//辅助空间,质数为true
        is_zhishu[0]=false;
        is_zhishu[1]=false;
        while(++index<n)
        {
            if(is_zhishu[index])//从头开始,对于质数,其倍数统统为false
            {
                int temp=1;
                while((++temp)*index<n)
                    is_zhishu[temp*index]=false;
            }
        }
        
        index=0;//统计个数
        int res=0;
        while(++index<n)
        {
            if(is_zhishu[index])
                res++;
        }
            
        return res;
    }
};

分析:

厄拉多塞筛法,另外被一个评论笑死。

原文地址:https://www.cnblogs.com/CJT-blog/p/10819467.html