Prime Friend
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2316 Accepted Submission(s): 463
Problem Description
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.
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
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
Author
iSea@WHU
Source
要注意的地方就是,数组要开大,isprime和prime都要开大很多。
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <string>
#include <cstring>
using namespace std;
int prm[20000010];
const int MAXV = 2e7;
bool isPrime[MAXV+1];
int size=0;
void getPrime()
{
memset(isPrime, true, sizeof(isPrime));
int sq = sqrt((double)MAXV) + 1;
int i,j,k;
for(i = 2;i <= sq; i++)
if(isPrime[i])
for(j = 2,k = MAXV/i+1;j < k;j++)
isPrime[i*j] = false;
for( i = 2 ; i <= MAXV; i++)
if(isPrime[i])
prm[size++] = i;
isPrime[0] = isPrime[1] = false;
}
int main()
{
long long T;
cin >> T;
getPrime();
int loy = 1;
while(T--)
{
int a,b;
scanf("%d%d",&a,&b);
//cin >> a >> b;
if(a>b)swap(a,b);
long long ans = -1;
for(int i=0;i<size-1;i++)
{
if(prm[i]>=a&&prm[i+1]>=b)
{
if((prm[i]-a) == (prm[i+1]-b))
{
ans = prm[i]-a;
break;
}
}
}
printf("Case %d: %lld\n",loy++,ans);
}
return 0;
}