2015
04-13

Prime Friend

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.

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

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

2
2 4
3 6

Case 1: 1
Case 2: -1

AC代码：

#include<iostream>
#include<vector>
#include<stdio.h>
#include<string.h>
using namespace std;

const int MAXN = 200000010;

int a[MAXN];
bool b[MAXN];
vector <int>sub[155];
int main(){
memset(b, 0, sizeof(b));
b[1] = 1;
for(int i = 2; i*i <= MAXN; i++){
if(b[i] == 1)
continue;
for(int j = i*2; j <= MAXN; j += i){
b[j] = 1;
}
}
int times = 0;
for(int i = 2; i <= MAXN; i++){
if(b[i] == 0){
a[times] = i;
times++;
}
}
for(int i = 0; i < times-1; i++){
int temp = a[i+1] - a[i];
if(temp>150)
continue;
sub[temp].push_back(a[i+1]);
}
int m;
scanf("%d", &m);
int sum = 0;
while(m--){
sum++;
long long x, y;
cin >> x >> y;
int temp1 = abs(x - y);
int temp2 = x > y ? x : y;
long long res = 0;
for(int i = 0;i < sub[temp1].size(); i++){
if(sub[temp1][i] >= temp2){
res = sub[temp1][i];
break;
}
}
printf("Case %d: ", sum);
if(res == 0)
puts("-1");
else
printf("%lld\n", res - temp2);
}
return 0;
}


1. simple, however efficient. A lot of instances it is difficult to get that a??perfect balancea?? among usability and appearance. I must say that youa??ve done a exceptional task with this. Also, the blog masses quite fast for me on Web explore.

2. 有两个重复的话结果是正确的，但解法不够严谨，后面重复的覆盖掉前面的，由于题目数据限制也比较严，所以能提交通过。已更新算法