204. Count Primes

来源:互联网 发布:logo在线制作软件 编辑:程序博客网 时间:2024/05/26 20:20

题目:

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;    }};

0 0
原创粉丝点击