Home Article Practice 计算n以内的素数

计算n以内的素数

2023-12-15 21:29  views:495  source:4669    

#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cout<<"请输入上限:";
cin>>n;
cout<<"以下为"<<n<<"以内的素数"<<endl;
vector<bool>nums(n+1,1);
nums[0]=0;
nums[1]=0;
for(int i=2;i<=n;i++){
if(nums[i]>0){
for(int j=i*i;j<=n;j+=i){
nums[j]=0;
}
}
}
int cnt=0;
for(int i=0;i<=n;i++){
if(nums[i]){
cout<<i<<' ';
cnt++;
if((cnt)%5==0){
cout<<endl;
}
}
}
return 0;
}



Disclaimer: The above articles are added by users themselves and are only for typing and communication purposes. They do not represent the views of this website, and this website does not assume any legal responsibility. This statement is hereby made! If there is any infringement of your rights, please contact us promptly to delete it.

字符:    改为:
去打字就可以设置个性皮肤啦!(O ^ ~ ^ O)