1013. 数素数 (20)

来源:互联网 发布:心知api怎么呐数据 编辑:程序博客网 时间:2024/05/16 18:56

令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
原创粉丝点击