前戏:本篇介绍一种特定数据范围内统计该段数据内所有质数的高效算法,埃拉托色尼筛选法。
正文:
1、埃拉托色尼筛选法:
埃拉托色尼筛选法(the Sieve of Eratosthenes)简称埃氏筛法,是古希腊数学家埃拉托色尼(Eratosthenes 274B.C.~194B.C.)提出的一种筛选法。 是针对自然数列中的自然数而实施的,用于求一定范围内的质数。
2、埃拉托色尼筛选法步骤:
(1)先把1删除(现今数学界1既不是质数也不是合数)
(2)读取队列中当前最小的数2,然后把2的倍数删去
(3)读取队列中当前最小的数3,然后把3的倍数删去
(4)读取队列中当前最小的数5,然后把5的倍数删去
(5)读取队列中当前最小的数7,然后把7的倍数删去
(6)如上所述直到需求的范围内所有的数均删除或读取
画个表格来解释下上面的步骤,比如要筛选出20内的所有质数的前三步:
3、code和运行结果
目的:筛选200内的所有质数
#include <iostream>
#include <bitset>
#include <string>
#include <cmath>
using namespace std;
#define MAX_NUM (200)
int main()
{
bitset<MAX_NUM + 1> bs; //bs[0] 不用,只有bs[1]~bs[200]
bs.set(); //把bs所有的bits置1
bs[1] = 0; //1不是质数
for (int i(2); i < MAX_NUM+1; i++) //i从2开始
{
//埃拉托色尼筛选过程
if (bs[i])
{
for (int j(i * 2); j < MAX_NUM + 1; j +=i )
bs[j] = 0;
}
}
cout << "质数个数:" << bs.count() << endl;
for (int i(1); i < MAX_NUM; i++)
{
if (bs[i])
cout << i << ",";
}
cout<<endl;
cout << endl;
cout << endl;
cout << endl;
cout << endl;
cout << endl;
return 0;
}
运行结果:
4、算法优化一:
理论依据:任何非质数,都会有一个因数不会大于他的算术平方根。所以优化后代码:
#include <iostream>
#include <bitset>
#include <string>
#include <cmath>
using namespace std;
#define MAX_NUM (200) //筛选200内的所有质数
#define S_NUM sqrt(MAX_NUM) //我们只需要筛选到sqrt(MAX_NUM) 就可以了
int main()
{
bitset<MAX_NUM + 1> bs; //bs[0] 不用,只有bs[1]~bs[200]
bs.set(); //把bs所有的bits置1
bs[1] = 0; //1不是质数
for (int i(2); i < S_NUM +1; i++) //i从2开始
{
//埃拉托色尼筛选过程
if (bs[i])
{
for (int j(i * 2); j < MAX_NUM + 1; j +=i )
bs[j] = 0;
}
}
cout << "质数个数:" << bs.count() << endl;
for (int i(1); i < MAX_NUM; i++)
{
if (bs[i])
cout << i << ",";
}
cout<<endl;
cout << endl;
cout << endl;
cout << endl;
cout << endl;
cout << endl;
return 0;
}
4、算法优化二:
根据观察,每次筛选的时候从这个数的平方开始筛选就可以。
#include <iostream>
#include <bitset>
#include <string>
#include <cmath>
using namespace std;
#define MAX_NUM (200) //筛选200内的所有质数
#define S_NUM sqrt(MAX_NUM) //我们只需要筛选到sqrt(MAX_NUM) 就可以了
int main()
{
bitset<MAX_NUM + 1> bs; //bs[0] 不用,只有bs[1]~bs[200]
bs.set(); //把bs所有的bits置1
bs[1] = 0; //1不是质数
for (int i(2); i < S_NUM +1; i++) //i从2开始
{
//埃拉托色尼筛选过程
if (bs[i])
{
for (int j(i * i); j < MAX_NUM + 1; j +=i )
bs[j] = 0;
}
}
cout << "质数个数:" << bs.count() << endl;
for (int i(1); i < MAX_NUM; i++)
{
if (bs[i])
cout << i << ",";
}
cout<<endl;
cout << endl;
cout << endl;
cout << endl;
cout << endl;
cout << endl;
return 0;
}