【模板】线性筛素数

\(O(n)\) 时间复杂度内筛出素数,即每个数只会被筛一遍。

题目跳转

代码

#include<bits/stdc++.h>
using namespace std;
typedef int ll;
uint8_t buf[1<<20],*p1,*p2;
#define gc() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<20,stdin),p1==p2)?EOF:*p1++)
ll rd(){
	ll x=0,f=1,ch=gc();
	while(ch<'0'||ch>'9'){
		if(ch=='-'){
            f=-1;
        }
        ch=gc();
	}
	while(ch>='0'&&ch<='9'){
		x=(x<<1)+(x<<3)+(ch-'0');
		ch=gc();
	}
	return x*f;
}
void write(ll x){
	if(x<0){
		x*=-1;
		putchar('-');
	}
	if(x>9){
		write(x/10);
	}
	putchar(x%10+'0');
}
ll n,q,cnt,pri[100000005];
bool ispri[100000005];
void ols(){
	ispri[0]=ispri[1]=true;
	for(ll i=2;i<=n;i++){
		if(!ispri[i]){
			pri[++cnt]=i;
		}
		for(ll j=1;j<=cnt&&i*pri[j]<=n;j++){
			ispri[i*pri[j]]=true;
			if(i%pri[j]==0){
				break;
			}
		}
	}
}
int main(){
	n=rd();
	ols();
	q=rd();
	while(q--){
		write(pri[rd()]);
		putchar('\n');
	}
	return 0;
}
posted @ 2026-10-17 16:25  beiciqi  阅读(6)  评论(0)    收藏  举报