您的位置:首页 > 其它

204. Count Primes

2016-06-03 22:24 176 查看
埃拉托色尼筛选法

埃拉托色尼选筛法(the
Sieve of Eratosthenes)简称埃氏筛法,是古希腊数学家埃拉托色尼(Eratosthenes
274B.C.~194B.C.)提出的一种筛选法。 是针对自然数列中的自然数而实施的,用于求一定范围内的质数,它的容斥原理之完备性条件是p=H~。

omplexity analysis

Computational complexity of the algorithm is O(nlog(log(n))). Strong proof of this fact is not too complex and based on several approximations from the prime numbers' theory. It can be found in [1].
The space complexity is O(n). Actually, on the modern hardware, algorithm will run out of memory much faster, than it would run out of time.

(1)先把1删除(现今数学界1既不是质数也不是合数)







(2)读取队列中当前最小的数2,然后把2的倍数删去



(3)读取队列中当前最小的数3,然后把3的倍数删去



(4)读取队列中当前最小的数5,然后把5的倍数删去



(5)如上所述直到需求的范围内所有的数均删除或读取







void runEratosthenesSieve(int upperBound) {
int upperBoundSquareRoot = (int)sqrt((double)upperBound);
bool *isComposite = new bool[upperBound + 1];
memset(isComposite, 0, sizeof(bool) * (upperBound + 1));
for (int m = 2; m <= upperBoundSquareRoot; m++) {
if (!isComposite[m]) {
cout << m << " ";
for (int k = m * m; k <= upperBound; k += m)
isComposite[k] = true;
}
}
for (int m = upperBoundSquareRoot; m <= upperBound; m++)
if (!isComposite[m])
cout << m << " ";
delete [] isComposite;
}

class Solution {
public:
int countPrimes(int n) {
vector<bool> prime(n,true);
prime[0]=false;
prime[1]=false;
for(int i=2;i<sqrt(n);i++)
{
if(prime[i])
{
for(int j=i*i;j<n;j+=i)
prime[j]=false;
}
}
return count(prime.begin(),prime.end(),true);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  素数 质数