204. Count Primes

题目:

Description:

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

题意:

统计小于非负整数n的素数的个数,素数不能被比它小的整数整除。


思路:

解题思路入提示二所示,埃拉托斯特尼筛法Sieve of Eratosthenes中,算法过程如下图所示,我们从2开始遍历到根号n,先找到第一个质数2,然后将其所有的倍数全部标记出来,然后到下一个质数3,标记其所有倍数,一次类推,直到根号n,此时数组中未被标记的数字就是质数。我们需要一个n-1长度的bool型数组来记录每个数字是否被标记,长度为n-1的原因是题目说是小于n的质数个数,并不包括n。 然后我们用两个for循环来实现埃拉托斯特尼筛法。

埃拉托斯特尼筛法

代码:312ms

class Solution {
public:
    int countPrimes(int n) {
        
        vector<bool> result(n-1, true);
        result[0] =false;
        int count = 0, last = sqrt(n);
        for(int i=2; i<=last; i++){
            if(result[i-1]){
                for(int j=i*i; j<n; j+=i){
                    result[j-1] = false;
                }
            }
        }
        for(int i=0; i<n-1; i++){
            if(result[i]){
                ++count;
            }
        }
        return count;
    }
};
代码:216ms

class Solution {
public:
    int countPrimes(int n) {
        
        if(n<=2){
            return 0;
        }
        vector<bool> result(n, false);
        int count = 1, last = sqrt(n);
        for(int i=3; i<n; i+=2){
            if(!result[i]){
                count++;
                if(i>last){
                    continue;
                }
                for(int j=i*i; j<n; j+=i){
                    result[j] = true;
                }
            }
        }
        
        return count;
    }
};
代码:16ms

class Solution {
public:
    int countPrimes(int n) {
        
        if(n<=2){
            return 0;
        }
        int count = n>>1, last = sqrt(n-1);
        bool *table = new bool[n];
        for(int i=3,j,step; i<=last; i+=2){
            if(!table[i]){
                for(step=i<<1, j=i*i; j<n; j+=step){
                    if(!table[j]){
                        table[j] = 1;
                        count--;
                    }
                }
            }
        }
        delete[] table;
        return count;
    }
};
代码:12ms

class Solution {
public:
    int countPrimes(int n) {
        
        if(--n < 2) return 0;
        int m = (n + 1)/2, count = m, k, u = (sqrt(n) - 1)/2;
        bool notPrime[m] = {0};
    
        for(int i = 1; i <= u;i++)
            if(!notPrime[i])
              for(k = (i+ 1)*2*i; k < m;k += i*2 + 1)
                  if (!notPrime[k])
                  {
                      notPrime[k] = true;
                      count--;
                  }
        return count;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值