素数筛法
用筛法求素数的基本思想是:把从1开始的、某一范围内的正整数从小到大顺序排列, 1不是素数,首先把它筛掉。剩下的数中选择最小的数是素数,然后去掉它的倍数。依次类推,直到筛子为空时结束。
如:有下列数
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
其中1不是素数,去掉。剩下的数中2最小,是素数,去掉2的倍数,余下的数是:
3 5 7 9 11 13 15 17 19 21 23 25 27 29
剩下的数中3最小,是素数,去掉3的倍数,如此下去直到所有的数都被筛完,求出的素数为:
2 3 5 7 11 13 17 19 23 29
#include<bits/stdc++.h>
#define range 1000000
using namespace std;
bool IsPrime[range];
int sushu[range];
void isprime(){
int i,j,cnt=1;
memset(IsPrime,true,sizeof(IsPrime)); //先假设所有的数都是素数
IsPrime[0]=IsPrime[1]=false;//0和1不是素数
for(int i=2;i<=range;i++){
if(IsPrime[i]==true){//如果是素数,则进数组
sushu[cnt++]=i;
for(j=i*2;j<=range;j+=i){//把素数的倍数都筛去
IsPrime[j]=false;
}
}
}
}
int m,n;
int main(){
cin>>m>>n;
isprime();
int count=0;
for(int i=m;i<=n;i++){
count++;
if(count%10==1)
cout<<sushu[i];
else if(count%10==0)
cout<<" "<<sushu[i]<<endl;
else
cout<<" "<<sushu[i];
}
}
常规方法:
这是一道主要考察输出格式处理的题
#include<bits/stdc++.h>
using namespace std;
bool isprime(int num){
if(num<2)
return false;
for(int i=2;i*i<=num;i++){
if(num%i==0)
return false;
}
return true;
}
int main(){
int m,n;
cin>>m>>n;
int cnt=0,num=2;
vector<int> v;
while(cnt<n){
if(isprime(num)){
cnt++;
if(cnt>=m)
v.push_back(num);
}
num++;
}
cnt = 0;
for(int i=0;i<v.size();i++){
cnt++;
if(cnt%10!=1)
cout<<" ";
cout<<v[i];
if(cnt%10==0)
cout<<endl;
}
}