So an integer has many prime friends, for example, 1 has infinite prime friends: 1, 2, 4, 6, 10 and so on. This problem is very simple, given two integers A and B, find the minimum common prime friend which will make them not only become primes but also prime neighbor. We say C and D is prime neighbor only when both of them are primes and integer(s) between them is/are not.
Each test case only contains two integers A and B.
Technical Specification
1. 1 <= T <= 1000
2. 1 <= A, B <= 150 Output For each test case, output the case number first, then the minimum common prime friend of A and B, if not such number exists, output -1. Sample Input
2 2 4 3 6Sample Output
Case 1: 1 Case 2: -1
#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
int prime[20000010];
bool iprime[20000010]={0};
int num=0;
void prim();
int main()
{
prim();
int i,j,k,count=1;
int t,a,b,temp;
cin>>t;
while(t--)
{
cin>>a>>b;//a,b大小没有顺序,,
if(a>b)
{
temp=a;
a=b;
b=temp;
}
temp=-1;
for(i=0;i<num-1;i++)
{
if(prime[i]>=a&&prime[i+1]>=b)//枚举
{
if((prime[i]-a)==(prime[i+1]-b))//差值相等就说明fu
{
temp=prime[i]-a;
break;
}
}
}
cout<<"Case "<<count<<": "<<temp<<endl;
count++;
}
}
void prim()
{
int i,j,flag;
iprime[1]=1;//线性筛法
for(i=2;i*i<=20000010;i++)
{
if(iprime[i]==1)
continue;
for(j=i*2;j<=20000010;j+=i)//保证只遍历一次
{
iprime[j]=1;
}
}
for(i=2;i<20000010;i++)
{
if(iprime[i]==0)
{
prime[num++]=i;
}
}
}