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 <= T <= 1000
- 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
题意:
给定一个a,当num+a为素数时,num是a素数朋友
现在给定两个数a,b,求一个num,使不仅a+num,b+num都是素数,并且两个素数之间所有数都不是素数,那么a+num,b+num是素数邻居
#include <iostream>
using namespace std;
const int maxn = 2e7+5;
int p[maxn];
bool prime[maxn];
int t=0;
void is_prime(){
memset(prime,1,sizeof(prime));
for(int i=2; i<maxn; i++){
if(prime[i]){
p[t++] = i;
}
for(int j=0; j<t && i*p[j]<maxn; j++){
prime[i*p[j]] = 0;
}
}
}
int main(){
int n,a,b;
is_prime();
scanf("%d",&n);
for(int i=1; i<=n; i++){
scanf("%d %d",&a,&b);
if(a>b) swap(a,b); //a<b
long long ans = -1;
for(int j=0; j<t; j++){
if(p[j]>=a && p[j+1]>=b){
if(p[j]-a == p[j+1]-b){
ans = p[j]-a;
break;
}
}
}
printf("Case %d: %lld\n",i,ans);
}
return 0;
}