概念
在 的时间复杂度内实现求 的质数的筛法
代码实现
#include <bits/stdc++.h>
using namespace std;
const int MAXN=1e8+10;
int n,book[MAXN],zs[int(1e7+10)],top;//book数组标记合数,zs数组记录质数
int main(){
cin>>n;
for(int i=2;i<=n;i++){
if(!book[i])zs[++top]=i;//记录质数
for(int j=1;j<=top&&i*zs[j]<=n;j++){
book[i*zs[j]]=1;//标记合数
if(i%zs[j]==0)break;//i已经被zs[j]筛过了,所以i乘上其他质数的结果一定会被zs[j]的倍数给删掉,所以可以直接break
}
}
for(int i=1;i<=top;i++)printf("%d ",zs[i]);
return 0;
}