素數距離問題
- 描述
- 現在給出你一些數,要求你寫出一個程序,輸出這些整數相鄰最近的素數,並輸出其相距長度。如果左右有等距離長度素數,則輸出左側的值及相應距離。
如果輸入的整數本身就是素數,則輸出該素數本身,距離輸出0- 輸入
- 第一行給出測試數據組數N(0<N<=10000)
接下來的N行每行有一個整數M(0<M<1000000), - 輸出
- 每行輸出兩個整數 A B.
其中A表示離相應測試數據最近的素數,B表示其間的距離。 - 樣例輸入
-
3 6 8 10
- 樣例輸出
-
5 1 7 1
11 1
-
-
public static void main(String[] args) { Scanner scan = new Scanner(System.in); int m = scan.nextInt(); int n; while (m-- > 0) { n = scan.nextInt(); for (int i = n - 1, j = n + 1; i <= j; i--, j++) { if (sushu(n)) { System.out.println(n + " " + 0); break; } else if (sushu(i)) { System.out.println(i + " " + (n - i)); break; } else if (sushu(j)) { System.out.println(j + " " + (j - n)); <span style="white-space:pre"> </span> break; } } System.out.println("\n"); } } static boolean sushu(int num) { int j; if (num == 1 || num == 0) return false; for (j = 2; j * j <= num; ++j) { if (num % j == 0) { break; } } if (j * j > num) { return true; } else { return false; } }