LeetCode:Count Primes

来源:互联网 发布:linux git生成ssh key 编辑:程序博客网 时间:2024/04/30 04:28

问题描述:

Count the number of prime numbers less than a non-negative number, n.返回n之前所有素数的个数。

思路:

朴素算法代码1显然不满足,初始想法就是朴素算法,没有通过,代码2为埃拉托斯特尼筛法,可以AC。

代码1:

初始想法:

class Solution {public:    int countPrimes(int n) {        if(n == 0 || n == 1 || n == 2)  return 0;        int result = 0;        for(int j = 2; j < n; ++j){            if(isPrimer(j)){                ++result;            }        }        return  result;    }    bool isPrimer(int k){        if(k % 2 == 0) return false;        else{            for(int i = 2; i * i < k; ++i){                if(k % i == 0 ) return false;            }        }        return true;    }};

显然超时!!!

Submission Result: Time Limit Exceeded More Details 

Last executed input:1500000








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

代码2:

class Solution {public:    int countPrimes(int n) {        vector<bool> num(n - 1, true);        int res = 0;         int len = sqrt(n);        num[0] = false;        for(int i = 2; i <= len; ++i){            if(num[i - 1]){                for(int j = i * i; j < n; j += i){                    num[j - 1] = false;                }            }        }        for(int i = 0; i < n - 1; ++i){            if(num[i])  ++res;        }        return res;    }};


0 0
原创粉丝点击