标签:c++
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[n];
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++
原文地址:http://blog.csdn.net/shenbo2030/article/details/45477819