Prime Friend
Describe
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
需要筛出一个足够大的素数表,而且保证不会超内存,所以用了bool类型。
#include<iostream>
#include<cstring>
using namespace std;
int prime[20000005];
bool flag[20000010];
bool flag2[200];
int main()
{
int top=0;
memset(flag,true,sizeof(flag));
memset(flag2,false,sizeof(flag2));
flag[0]=flag[1]=false;
for(int i=2; i<=20000000; i++)
{
if(flag[i])
{
prime[top++]=i;
for(int j=i*2; j<=20000000; j+=i)
{
flag[j]=false;
}
}
}
for(int i=0;i<top-1;i++)
{
if(prime[i+1]-prime[i]<=150)
{
flag2[prime[i+1]-prime[i]]=true;
}
}
int t;
cin>>t;
for(int i=1;i<=t;i++)
{
int m,n,ans=-1;
cin>>m>>n;
cout<<"Case "<<i<<": ";
if(m>n) swap(m,n);
if(!flag2[n-m]||m==n) cout<<"-1"<<endl;
else
{
for(int i=0;i<top-1;i++)
{
if(prime[i+1]-prime[i]==n-m&&m<=prime[i])
{
ans=prime[i]-m;
break;
}
}
cout<<ans<<endl;
}
}
return 0;
}