欧拉筛线性筛质数
欧拉筛线性筛质数
经典题解
我的乱搞筛法和欧拉线性筛法的速度对比:
模版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;
}
乱搞筛法
#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])
continue;
pr[++x] = i;
a[i]=1;
for (int j = i * 2; j <= n; j += i)
{
a[j] = 1;
}
}
for (int i = 1; i <= q; i++)
{
int d=read();
cout<<pr[d]<<'\n';
}
return 0;
}
任何时候都有比放弃更好的选择。