針對這道題,首先,我們應該找到PM —PN之間的素數。但是,我們不可能直接知道,第幾個素數是幾。必須經過篩選才能知道。因此,我們需要一個變量控制,我們找到的多少個素數。 只有當這個變量等於M時,才讓程序輸出,等於N時,終止程序。
細節注意:
題目要求我們輸出時候,末尾不能有空格。
所以我們要考慮幾種特殊情況。
- 輸入 數字爲 1 1 時候:
這個需要特殊處理。直接輸出2,且後面無空格。 - 輸入的數字,導致要找的素數個數,正好是10的倍數。切記最後一行雖然是該換行了,但是,後面已經沒有數字了,就不能再換行了。
- 輸入的數字,導致要找的素數個數除以10,結果餘1。這個時候,切記最後一個數字一定不要有空格。
這道題,難度不大,主要是輸出格式比較噁心。
下面看代碼:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sca = new Scanner(System.in);
int min = sca.nextInt();
int max = sca.nextInt();
int count = 1;
int printCount = 0;
boolean isprimeNumber = true;
if(min == 1 && max == 1) {
System.out.print(2);
return ;
}
if(min == 1) {
printCount++;
System.out.print(2 + " ");
}
for(int i = 3; ; i++) {
if(count == max) break;
for(int j = 2; j < Math.sqrt(i) + 1; j++) {
if(i % j == 0) {
isprimeNumber = false;
break;
}
}
if(isprimeNumber) {
count++;
if(count >= min) {
printCount++;
if(count == max) {
System.out.print(i);
}else {
if(printCount % 10 == 0) {
System.out.print(i);
System.out.println();
}else {
System.out.print(i + " ");
}
}
}
}
isprimeNumber = true;
}
}
}
在這裏插入代碼片