令 P 表示第 i 个素数。现任给两个正整数 M≤N≤10,请输出 P 到 P 的所有素数。
输入格式:
输入在一行中给出 M 和 N,其间以空格分隔。
输出格式:
输出从 P 到 P 的所有素数,每 10 个数字占 1 行,其间以空格分隔,但行末不得有多余空格。
输入样例:
5 27
输出样例:
11 13 17 19 23 29 31 37 41 4347 53 59 61 67 71 73 79 83 8997 101 103
思路
我的方法是读取一个数处理一个数。
如果这个数是素数,则素数计数器counter++。
当counter达到题目要求的区间时,就输出元素。
注意每10个输出要换一行,我用nextLine变量来记录输出了几个素数。
代码
#include <iostream>#include <algorithm>using namespace std;int isPrime(int n) {if(n <= 1) return 0;for(unsigned i = 2; i * i <= n; i++) {if(n % i == 0) return 0;}return 1;}int main() {int start = 0, end = 0;cin >> start >> end;int counter = 0, nextLine = 0;for(int i = 2; counter != end; i++) {if( isPrime(i) ) counter++;else continue;if(counter > end) break;if( counter >= start && counter <= end ) {nextLine++;printf("%d", i);if(nextLine % 10 != 0 && counter != end) printf(" ");else printf("\n");}}return 0;}
