高效寻找质数——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++中属于不错的。
思路:给出要筛数值的范围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; }
相关文章推荐
- the Sieve of Eratosthenes
- Algorithm: Sieve of Eratosthenes
- The Sieve of Eratosthenes
- Sieve Of Eratosthenes求素数(埃拉托斯特尼筛法)
- The Sieve of Eratosthenes (素数筛选法)
- Sieve of Eratosthenes
- algorithm@ Sieve of Eratosthenes (素数筛选算法) & Related Problem (Return two prime numbers )
- 素数筛法【Sieve Of Eratosthenes + Sieve Of Euler】
- Sieve_of_Eratosthenes
- 09 Sieve of Eratosthenes
- [经典算法] Eratosthenes筛选求质数
- 使用Eratosthenes 方法找出指定范围内的所有质数
- sieve of Eratosthenes——一种寻找素数的方法
- 用Eratosthenes筛法查找质数
- Eratosthenes筛选求质数
- 算法:Eratosthenes 筛选求质数
- 生成质数的好方法:sieve of eratosthenes
- 找质数算法(Sieve of Eratosthenes筛法)
- 找质数算法(Sieve of Eratosthenes筛法)
- Eratosthenes 筛选求质数