(2)M - 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.
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
题意:输入T,表示有T个测试数据,输入a,b,寻找一个最小的素数s使得a+s和b+s为素数并且为相邻的素数,如果有输出该素数,否则输出-1,思路:我完全想不出来,后来才知道,因为a,b的差值等于a+s和b+s的差值,所以直接打表出素数一个个找就可以。(因为打表要打到两千万多,而我当时只会一般的筛法,结果超时了,然后又去学习线性筛法)

#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
int prime[20000010];
bool iprime[20000010]={0};
int num=0;
void prim();
int main()
{
 prim();
 int i,j,k,count=1;
 int t,a,b,temp;
 cin>>t;
 while(t--)
 {
  cin>>a>>b;//a,b大小没有顺序,,
  if(a>b)
  {
   temp=a;
   a=b;
   b=temp;
  }
  temp=-1;
  for(i=0;i<num-1;i++)
  {
   if(prime[i]>=a&&prime[i+1]>=b)//枚举
   {
    if((prime[i]-a)==(prime[i+1]-b))//差值相等就说明fu
    {
     temp=prime[i]-a;
     break;
    }
   }
  }
  cout<<"Case "<<count<<": "<<temp<<endl;
  count++;
 }
}
void prim()
{
 int i,j,flag;
  iprime[1]=1;//线性筛法
 for(i=2;i*i<=20000010;i++)
 {
  if(iprime[i]==1)
  continue;
  for(j=i*2;j<=20000010;j+=i)//保证只遍历一次
  {
   iprime[j]=1;
  }
 }
 for(i=2;i<20000010;i++)
 {
  if(iprime[i]==0)
  {
   prime[num++]=i;
  }
 }
 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值