HDU 3823 Prime Friend(大素数)


Prime Friend
Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2619    Accepted Submission(s): 523
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.
 
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

 
Author
iSea@WHU
 
Source
The 6th Central China Invitational Programming Contest and 9th Wuhan University Programming Contest Final 
原題リンク:http://acm.hdu.edu.cn/showproblem.php?pid=3823
2つの数a,bが既知で、最小の数cを求めて、a+cとb+cはすべて素数で、しかも彼らの間に素数がありません
ACコード:
#include  <stdio.h>
#include <string.h>
#include <stdbool.h>
#define maxn 21000000
bool isprime[maxn];
long long prime[maxn],nprime;
void getprime(void)
{
    memset(isprime,true,sizeof(isprime));
    nprime=0;
    long long i,j;
    for(i=2;i<maxn;i++)
    {
        if(isprime[i])
        {
            prime[nprime++]=i;
            for(j=i*i;j<maxn;j+=i)
            {
                isprime[j]=false;
            }
        }
    }

}

bool isd[150];
int main()
{
    getprime();
    int i,t,temp,ca=0;
    long long a,b;
    for(i=1;i<nprime;i++)
    {
        if(prime[i]-prime[i-1]<150)
        {
            isd[prime[i]-prime[i-1]]=1;
        }
    }
    scanf("%d",&t);
    while(t--)
    {
        scanf("%I64d%I64d",&a,&b);
        if(a>b)
        {
            temp=a;
            a=b;
            b=temp;
        }
        long long ans=-1,d=b-a;
        printf("Case %d: ",++ca);
        if(!isd[d]||a==b)
        {
            printf("-1
"); continue; } for(i=1;i<nprime;i++) { if(prime[i]-prime[i-1]==d&&a<=prime[i-1]) { ans = prime[i-1]-a; break; } } printf("%I64d
",ans); } return 0; }