素數距離問題
時間限制:3000 ms | 內存限制:65535 KB
難度:2
描述
現在給出你一些數,要求你寫出一個程序,輸出這些整數相鄰最近的素數,並輸出其相距長度。如果左右有等距離長度素數,則輸出左側的值及相應距離。如果輸入的整數本身就是素數,則輸出該素數本身,距離輸出0
- 輸入
- 第一行給出測試數據組數N(0<N<=10000)
接下來的N行每行有一個整數M(0<M<1000000), - 輸出
- 每行輸出兩個整數 A B.
其中A表示離相應測試數據最近的素數,B表示其間的距離。 - 樣例輸入
3
6
8
10
樣例輸出
5 1
7 1
11 1
import java.io.BufferedInputStream;
import java.util.Scanner;
public class Main {
public static boolean IsPrimer(int x){
if(x<=1)
return false;
if(x==2)
return true;
if(x%2==0||x==1)
return false;
for(int i=3;i<=Math.sqrt(x);i++)
if(x%i==0)
return false;
return true;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner cin = new Scanner(new BufferedInputStream(System.in));
int n = cin.nextInt();
while(n-->0){
int num = cin.nextInt();
int T = -1;
int N = 1;
if(IsPrimer(num))
System.out.println(num+" "+0);
else{
while(!IsPrimer(num)){
num = num+T*N;
N++;
T = -T;
}
System.out.println(num+" "+N/2);
}
}
}
}