1013 数素数

素数筛法

用筛法求素数的基本思想是:把从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;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值