数论函数整理
Yuhaochen666 · · 个人记录
筛法
试除法
过程
对于每个数使用试除法,从
经过
筛出
时限
代码
#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;
}
埃拉托斯特尼筛法(埃氏筛)
过程
注意到试除法中尝试用合数来筛,而实际上我们只需要用质数来筛。因此考虑在一个数被判定为质数时将它的倍数打上标记,最终没被标记的就是质数。
时间复杂度
代码
欧拉筛(线性筛)
过程
代码