筛法
试除法
过程
对于每个数使用试除法,从 中寻找 的因数。
经过 特判优化后可以达到时间复杂度 以内判断一个数是否为质数。
筛出 范围内的质数总时间复杂度约为 ,空间复杂度为 。
时限 时最大数据范围为 左右。
代码
#include <bits/stdc++.h>
using namespace std;
inline bool zs(int x)
{
if((x%6==1)||(x%6==5))
{
for(int i=1;(i*i*36-i*12)<x;++i)
{
if((x%(i*6-1)==0)||(x%(i*6+1)==0))
{
return 0;
}
}
return 1;
}
return 0;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n;
cin>>n;
if(n>=2)
{
cout<<2<<'\n';
if(n>=3)
{
cout<<3<<'\n';
}
}
for(int i=5;i<=n;i++)
{
if(zs(i))
{
cout<<i<<'\n';
}
}
return 0;
}埃拉托斯特尼筛法(埃氏筛)
过程
注意到试除法中尝试用合数来筛,而实际上我们只需要用质数来筛。因此考虑在一个数被判定为质数时将它的倍数打上标记,最终没被标记的就是质数。
时间复杂度 ,空间复杂度 。
代码
欧拉筛(线性筛)
过程
代码