http://acm.hdu.edu.cn/showproblem.php?pid=3823
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
题目大意: 给出a和b, 找出一个数k, 使得a+k和b+k均为素数,且这两个素数相邻的素数。没有输出-1。
思路:暴力筛取20000000以内的素数,b+k和a+k之间的差距依然是b-a,而b-a是已知的,(我们总让b>a)因此我们对素数表从前向后枚举两个相邻素数之间的差值,若其等于b-a就是我们要找到的。比如此时prime[i]-prime[i-1]=b-a,那么结果就是prime[i-1]-a或者说prime[i]-b。因为结果是大于等于0的数,因此隐含了另一个条件:a<=prime[i-1]。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#define INF 0x3f3f3f3f
typedef long long ll;
using namespace std;
const ll maxn=20000000;
int prime[20000005];//存储素数
bool vis[20000010];//标记数组
bool flag[155];
int k=-1;
int main()
{
for(ll i=2;i<=maxn;i++)
{
if(!vis[i])
{
prime[++k]=i;
for(ll j=i*i;j<=maxn;j+=i)//用ll 防止溢出
vis[j]=1;
}
}
for(int i=1;i<=k;i++)
if(prime[i]-prime[i-1]<150)
flag[prime[i]-prime[i-1]]=1;//标记相连的两个素数之间的差距
int t;
scanf("%d",&t);
int times=0;
while(t--)
{
int a,b;
scanf("%d %d",&a,&b);
printf("Case %d: ",++times);
if(a>b)
swap(a,b);
int temp=-1,dis=b-a;
if(!flag[dis]||a==b)
printf("-1\n");
else
{
for(int i=1;i<=k;i++)
{
if(prime[i]-prime[i-1]==dis&&a<=prime[i-1])
{
temp=prime[i-1]-a;
break;
}
}
printf("%d\n",temp);
}
}
return 0;
}