題目描述
令Pi表示第i個素數。現任給兩個正整數M <= N <= 10000,請輸出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
本題的解題關鍵:
1.判斷是否爲素數
2.素數是否在要求的區間
注意事項:
1.每一行最後一個數字不要空格
2.每十個數字換一次行
下面是代碼實現
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt();
int n = scanner.nextInt();
int temp = 0;//標記第i個素數
int t = 1;//換行標識符
for (int i = 2;; i++) {
if(m!=n) {
if (isPrime(i)) {
temp++;
}
if (temp >= m && isPrime(i) && temp != n) {
if (t % 10 == 0) {
System.out.print(i);
System.out.println();
t = 1;
continue;
}
System.out.print(i + " ");
t++;
}
if (temp == n) {
System.out.print(i);
break;
}
}else {
if (isPrime(i)) {
temp++;
}
if(temp == m) {
System.out.print(i);
break;
}
}
}
scanner.close();
}
public static boolean isPrime(int n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0)
return false;
}
return true;
}
}