Besides the ordinary Boy Friend and Girl Friend, here we define a more academic kind of friend: Prime Friend. We call a nonnegative integer A is the integer B’s Prime Friend when the sum of A and B is a prime.
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.
Input
The first line contains a single integer T, indicating the number of test cases.
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 6
Sample Output
Case 1: 1 Case 2: -1
题解:这道题素数范围筛选很重要,一百万会 WA,二百万超内存,一百九十万就能AC,也是很玄学了;
这题的素数筛法选区也很重要,否者会超时;
代码:
#include <iostream>
#include <string>
#include <cstring>
#include <map>
#include <string.h>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
using namespace std;
#define maxn 19000000
bool isprime[maxn];
long long prime[maxn],nprime;
void getprime(void)
{
memset(isprime,true,sizeof(isprime));
nprime=0;
long long i,j;
for(i=2;i<maxn;i++)
{
if(isprime[i])
{
prime[nprime++]=i;
for(j=i*i;j<maxn;j+=i)
{
isprime[j]=false;
}
}
}
}//666的素数表;
bool isd[150];
int main()
{
getprime();
int T,a,b;
for(int i=1;i<nprime;i++)
{
if(prime[i]-prime[i-1]<150)
{
isd[prime[i]-prime[i-1]]=1;
}
}
cin>>T;
int num=1;
while(1)
{
if(num>T) break;
else { printf("Case %d: ",num); num++;}
cin>>a>>b;
if(a>b)
{
int t;
t=a,a=b,b=t;
}
long long ans=-1,d=b-a;
if(!isd[d] || a==b)
{
cout<<"-1"<<endl;
continue;
}
for(int i=1;i<nprime;i++)
{
if(prime[i]-prime[i-1]==d && a<=prime[i-1])
{
ans=prime[i-1]-a;
break;
}
}
cout<<ans<<endl;
}
}