[PAT乙级] Practise 1013 数素数

PAT (Basic Level) Practice (中文)1013

1013 数素数

Pi 表示第 i 个素数。现任给两个正整数 MN≤104,请输出 PMPN 的所有素数。

输入格式:

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

输出格式:

输出从 PMPN 的所有素数,每 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

思路:

找到第 2 ~ n 个素数,在输出时用 j 计数分组即可。

代码:

#include <iostream>
#include <vector>
using namespace std;
bool isP(int a) {
    for (int i = 2; i * i <= a; i++)
        if (a % i == 0)
            return false;
    return true;
}
int main() {
    int m, n;
    int number = 2;
    vector<int> hash;
    int ct = 0;
    cin >> m >> n;
    while (ct<n) {
        if (isP(number)) {
            hash.push_back(number);
            ct++;
        } 
        number++;
    }

    int j = 1;
    for (int i = m-1; i < n; i++,j++) {
        cout << hash[i];
        if (i != n-1 &&  j % 10 != 0)
            cout << " ";
        else if (j % 10 == 0)
            cout << endl;
    }
    return 0;
}
posted @ 2020-03-14 16:21  eisuto  阅读(108)  评论(0编辑  收藏  举报