1013. 数素数 (20)

令Pi表示第i个素数。现任给两个正整数M <= N <= 104,请输出PM到PN的所有素数。

输入格式:

输入在一行中给出M和N,其间以空格分隔。

输出格式:

输出从PM到PN的所有素数,每10个数字占1行,其间以空格分隔,但行末不得有多余空格。

输入样例:
5 27
输出样例:
11 13 17 19 23 29 31 37 41 43
47 53 59 61 67 71 73 79 83 89
97 101 103

 #include<iostream>
#include<math.h>
using namespace std;
int main(){

    int m,n;
    cin>>m;
    cin>>n;
    int count = 0,c = 0;
    bool judge = true;
    //测试数据不一定为int型
    for(int i = 2;i<105535;i++){
        judge = true;
        for(int j = 2;j<=(int)sqrt(i);j++){
            if(i%j==0) judge = false;
        }
        //是素数 ,11的时候count为5 (count从2这个素数开始计数)
        if(judge) {
            count++; 
        }
        if(count<=n&&count>=m&&judge){
            cout<<i;

        //判断是否是10个数里面的最后一个 
        if(count<=5){
            if(count!=n) cout<<" ";
        }else{
                if((count-m+1)%10!=0&&count!=n) cout<<" ";
            //  cout<<"--"<<count<<endl;
        }
        //十个数换一行,
        //极端情况处理 刚好10,或者20个数时:c!=n
            c++;
            if(c%10==0&&c!=n){
                cout<<endl;
            }
        } 
            //查找到所需个数后,结束查找
            if(count==(n+m)) break;
        }
    return 0;
}

第二次做:

#include<iostream>
#include<math.h>
using namespace std;
int main(){
    int left, right, count = 0;
    bool judge ;
    cin >> left;
    cin >> right;
    for ( int i = 2;i < 165535; i++ ){
        judge = true;
        for ( int j = 2; j <= (int)sqrt(i); j++ ){
            if ( i%j == 0 ){
                judge = false;
                break; 
            }
        }
        if ( judge ) count++;
        //被选中的素数 
        if ( count <= right && count >= left && judge ){
            cout << i;
            //空格 
            if (( count - left + 1 ) % 10 != 0 && count != right) cout << " ";
            //换行 
            if (( count - left + 1 ) % 10 == 0 && count != right) cout << endl;
        } 
        if (count == right) break;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值