您的位置:首页 > 编程语言 > C语言/C++

高效寻找质数——Sieve of Eratosthenes

2015-05-04 10:53 776 查看
Sieve of Eratosthenes-埃拉托斯特尼筛法,简称埃氏筛。

思路:给出要筛数值的范围n,找出

以内的素数

。先用2去筛,即把2留下,把2的倍数剔除掉;再用下一个素数,也就是3筛,把3留下,把3的倍数剔除掉;接下去用下一个素数5筛,把5留下,把5的倍数剔除掉;不断重复下去......,直到其小于等于



示意图如下:





实例:LeetCode上寻找质数的一个问题(https://leetcode.com/problems/count-primes/)。

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

PS:当n=1500000,LeetCode评测为58ms,运行效率在C++中属于不错的。

int countPrimes(int n)
{
bool IsPrimes
;
int PrimesNum=0;
for(int i=2; i<n; i++)
IsPrimes[i]=true;
// remove the times of primes.
for(int i=2; i<=sqrt(n); i++)
if(IsPrimes[i])
for(int j=2; j*i<=n; j++)
IsPrimes[j*i]=false;
// count the number of primes.
for(int i=2; i<n; i++)
if(IsPrimes[i])
PrimesNum++;
return PrimesNum;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++