初级算法:计算质数个数

计数质数
统计所有小于非负整数 n 的质数的数量。

示例:

输入: 10
输出: 4
解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。

思路一:
暴力法,两个循环 超时 不通过编译 时间复杂度

class Solution {
public:
    int countPrimes(int n) {
       int cnt=0;
        for(int i=2;i<n;++i){
            bool sign=true;
            for(int j=2;j<i;++j){
                if(i%j==0){
                    sign=false;
                    break;
                } 
            }
            if(sign)cnt++;
        }
        return cnt;
    }
};

优化1,第二个循环,判定条件改为 j*j<=i ,减少循环次数 可以通过 不超时

class Solution {
public:
    int countPrimes(int n) {
       int cnt=0;
        for(int i=2;i<n;++i){
            bool sign=true;
            for(int j=2;j*j<=i;++j){
                if(i%j==0){
                    sign=false;
                    break;
                } 
            }
            if(sign)cnt++;
        }
        return cnt;
    }
};

优化二:排除掉所有偶数 减少循环

class Solution {
public:
    int countPrimes(int n) {
        if(n<3)
            return 0;
        int cnt=1;
        for(int i=3;i<n;i++){
            if((i&1)==0)
                continue;
            bool sign =true;
            for(int j=3;j*j<=i;j+=2){
                if(i%j==0)
                {
                    sign=false;
                    break;
                }
            }
            if(sign)cnt++;
        }
        return cnt;
    

优化3:厄拉多塞筛选法 相当好用

class Solution {
public:
    int countPrimes(int n) {
        int cnt=0;
        //其实全部设置为true
        vector<bool>signs(n,true);
        for(int i=2;i<n;++i){
            //如果此位为质数 cnt+1 此质数的整数倍均被赋为false
            if(signs[i]){
                cnt++;
                for(int j=i+i;j<n;j+=i){
                    signs[j]=false;
                }
            }
        }
        return cnt;
    }
};
发布了36 篇原创文章 · 获赞 0 · 访问量 614

猜你喜欢

转载自blog.csdn.net/weixin_43199933/article/details/103113196