204. Count Primes
2016-06-03 22:24
176 查看
埃拉托色尼筛选法
埃拉托色尼选筛法(the
Sieve of Eratosthenes)简称埃氏筛法,是古希腊数学家埃拉托色尼(Eratosthenes
274B.C.~194B.C.)提出的一种筛选法。 是针对自然数列中的自然数而实施的,用于求一定范围内的质数,它的容斥原理之完备性条件是p=H~。
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)如上所述直到需求的范围内所有的数均删除或读取
埃拉托色尼选筛法(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); } };
相关文章推荐
- C#查找素数实现方法
- java使用筛选法求n以内的素数示例(java求素数)
- java求100以内的素数示例分享
- 判断一个数是不是素数的方法
- JavaScript实现找质数代码分享
- C++回文数及素数问题计算方法
- c#求范围内素数的示例分享(c#求素数)
- GO语言求100以内的素数
- JavaScript判断数字是否为质数的方法汇总
- Java实现求小于n的质数的3种方法
- Java列出2到100之间所有素数的方法
- Python素数检测实例分析
- Python实现高效求解素数代码实例
- 使用Python判断质数(素数)的简单方法讲解
- Python素数检测的方法
- Python实现求最大公约数及判断素数的方法
- Go语言生成素数的方法
- python实现挑选出来100以内的质数
- python学习--埃拉托斯特尼筛法求素数
- Java 求1-100范围内的素数