尤拉篩線性篩質數
經典題解
我的亂搞篩法和尤拉線性篩法的速度對比:
模版code
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100000009;
bool a[100000009];
int read()
{
int x=0,f=1;char ch=getchar();
while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
while(isdigit(ch)){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int n, q;
bool isprime(int x)
{
if (x < 2)
return false;
for (int i = 2; i * i <= x; i++)
{
if (x % i == 0)
return false;
}
return true;
}
int pr[maxn], x = 0;
int main()
{
std::ios::sync_with_stdio(0);
std::cout.tie(0);
n=read(), q=read();
a[1]=1;
for (int i = 2; i <= n; i++)
{
if(!a[i])
pr[++x] = i;
a[i]=1;
for (int j = 1; j <= x&&i*pr[j]<=n; j ++)
{
a[i*pr[j]]=1;
if(i%pr[j]==0)
break;
}
}
for (int i = 1; i <= q; i++)
{
int d=read();
cout<<pr[d]<<'\n';
}
return 0;
}