B1013 数素数 (20分)

1013 数素数 (20分)

令 P​i表示第 i 个素数。现任给两个正整数 M≤N≤10^4,请输出 P​M到 P
​N的所有素数。
输入格式:
输入在一行中给出 M 和 N,其间以空格分隔。

输出格式:
输出从 P
​M
​​ 到 P
​N
​​ 的所有素数,每 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

分析

求素数进行输出,

  • 使用筛选法求出素数的素组。《算法笔记》∂ p162。
  • 遍历输出
  • 49 ms
#include <iostream>
using namespace std;
const int maxn = 1000010;
int m [maxn];
void isPrime(){
    for (int i=2; i<maxn; i++) {
        for (int j=2*i; j<maxn&&j+i<maxn; j+=i) {
            m[j] = 1; }
    }
}
int main(){
    int p,q;
    cin >> p >> q;
    isPrime();
    int j=0;
    int co=0;
    for (int i=1;i<=maxn;i++){        
        if(m[i]==0){
            if(co>=p&&co<=q){
            if(j%10!=0)cout << " ";
            cout << i;        
            if (j%10==9) {
                cout << endl;
            }  j++;
            }
            if(co==q){
                break;
            }
            co++ ;            
        }
    }
}

代码优化:

学习算法笔记代码

  • 整洁
  • 复杂度更低一些
  • 10 ms
#include <iostream>
using namespace std;
const int maxn = 1000010;
int co=0;
bool arr [maxn];
int pp [maxn];
void isPrime(int n){
    for (int i=2; i<maxn; i++) {
        if (arr[i] == false){
            pp[co++]=i;
            if(co>n){
                break;
            }
            for (int j =i+i; j<maxn; j+=i) {
                arr[j] = true;
            }
        }
    }
}
int  main(){
    int q,p,l=0;
    cin >> q >>p;
    isPrime(p);
    for (int i=q-1; i<p; i++) {
        cout << pp[i];
        l++;
        if (l%10!=0&&i<p-1) {
            cout << " ";
        }else cout << endl;
    }
    return 0;
}

发布了91 篇原创文章 · 获赞 9 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/WeDon_t/article/details/103817874
今日推荐