c++实现最快求质数个数以及质数的方法
程序员文章站
2024-03-14 20:58:59
...
本博文利用了筛选法实现了质数的求取,并且利用数学分析的特性进行了代码优化,使得速度获得极大提升,不可多得
#include<iostream>
#include<bitset>
#include<cmath>
#include<iostream>
using namespace std;
//最快的方法筛选法求质数
int main()
{
int const max_number(100);
const int max_test((int)sqrt((double)max_number));
bitset<max_number + 1> numbers;
numbers.set();
numbers[1] = 0;
for (int i = 1; i != max_test; ++i)
{
if (numbers[i]) {
for (int j = i * i; j < max_number + 1; j += i)
numbers[j] = 0;
}
}
cout << "少于100质数的个数:" << numbers.count()<<endl;
for (int i = 1; i != max_number; ++i)
{
if (numbers[i]) {
cout << i << " ";
}
}
system("pause");
return 0;
}