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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值