Go to: My own blog
topic
Luogu P3383 Linear Sieve Prime Number
answer
The essence of sieve method is to mark composite numbers, that is, to mark all multiples of each number. However, when marking, a composite number will be marked multiple times by all its prime factors, resulting in a waste of time. Therefore, consider that each composite number is only marked by its own smallest prime factor.
Algorithm flow: Use v[i] to represent the smallest prime factor of i, use all prime numbers p not greater than v[i] to mark the composite number i*p, and update v[i*p]=p.
The number of prime numbers between 1 and n is approximately .
Code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e8+5;
const int maxp=5e6;
int n,m,q;
int v[maxn],prime[maxp];
inline void get_prime()
{
for(int i=2;i<=n;i++) //注意从2开始循环
{
if(!v[i]) {v[i]=i; prime[++m]=i;}
for(int j=1;j<=m;j++)
{
if(prime[j]>v[i]||prime[j]*i>n) break;
v[i*prime[j]]=prime[j];
}
}
}
int main()
{
scanf("%d%d",&n,&q);
get_prime();
for(int i=1;i<=q;i++)
{
int k; scanf("%d",&k);
printf("%d\n",prime[k]);
}
return 0;
}