输入描述:
输入在一行中给出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
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {//注意while处理多个case
int N = in.nextInt();
int M = in.nextInt();
List<Integer> list = jisuan(N, M);
printNum(N, M, list);
}
}
//计算素数
private static List<Integer> jisuan(int N, int M) {
List<Integer> list = new ArrayList<Integer>();
for (int a = 2; a < Integer.MAX_VALUE; a++) {
int temp = (int) Math.sqrt(a);
if (a == 2) {
list.add(a);
} else {
for (int i = 2; i <= temp; i++) {
if (a % i == 0) {
break;
}
if (i >= temp) {
list.add(a);
}
}
}
if (list.size() == N + M) {
break;
}
}
return list;
}
// 格式输出
static void printNum(int N, int M, List<Integer> list) {
int line = 0;
if (N - 2 >=0) {
for (int i = N - 2; i < M - 1; i++) {
if (line % 10 == 9 || i == M - 2) {
System.out.print(list.get(i));
} else {
System.out.print(list.get(i) + " ");
}
line++;
if (line % 10 == 0) {
System.out.println();
}
}
} else {
for (int i = N-1; i < M ; i++) {
if (line % 10 == 9 || i == M-1) {
System.out.print(list.get(i));
} else {
System.out.print(list.get(i) + " ");
}
line++;
if (line % 10 == 0) {
System.out.println();
}
}
}
}
}