您的位置:首页 > 其它

LeetCode: Count Primes(计算n以内素数个数:高效算法)

2016-07-22 11:07 429 查看

LeetCode: Count Primes(计算n以内素数个数:高效算法)

Description:

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

A prime number is a natural number that has exactly two distinct natural number divisors: 1 and itself.

https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity

埃拉托色尼筛选法:Sieve of Eratosthenes。

时间复杂度:O(n log log n)。

下面是图示过程,还有leetcode上hint用java编写的。



class Solution {
public:
int countPrimes(int n) {
if(!n||n==1)  return 0;
vector<bool> isPrime(n,true);
// Loop's ending condition is i * i < n instead of i < sqrt(n)
// to avoid repeatedly calling an expensive function sqrt().
for(int i=2;i*i<n;++i)
{
if(!isPrime[i]) continue;
//填表起点i*i,如3*3,因为3*2已填,步长+i
for(int j=i*i;j<n;j+=i)
{
isPrime[j]=false;
}
}
int count=0;
for(int i=2;i<n;++i)
{
if(isPrime[i])  ++count;
}
return count;
}
};


别人代码用的i*i与n比较,值得学习: Loop’s ending condition is i * i < n instead of i < sqrt(n) to avoid repeatedly calling an expensive function sqrt().
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode