nyoj 素數距離
素數距離問題
時間限制: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
#include <iostream>
#include <cmath>
using namespace std;
bool is_Primer(int x)
{
if(x<2)
return false;
for(int i=2;i<=sqrt(x);++i)
if(x%i==0)
return false;
return true;
}
int main()
{
int n;
cin>>n;
while(n--)
{
int x;
cin>>x;
if(x==1)
{
cout<<"2"<<" "<<"1"<<endl;
continue;
}
if(x==0)
{
cout<<"2"<<" "<<"2"<<endl;
continue;
}
if(is_Primer(x))
{
cout<<x<<" "<<"0"<<endl;
continue;
}
int left;
for(int i=x-1;i>1;--i)
if(is_Primer(i))
{
left=i;
break;
}
int right;
for(int i=x+1;;++i)//不要加循環終止條件,因為題目沒有說最小的值是多少,加了就wronganswer。。。一個大神給我指導的,
if(is_Primer(i))
{
right=i;
break;
}
if(right-x<x-left)
cout<<right<<" "<<right-x<<endl;
else if(right-x>=x-left)
cout<<left<<" "<<x-left<<endl;
}
return 0;
}
nyoj 素數距離