HDU 3823 Prime Friend(线性欧拉筛+打表)
Posted qdu-lkc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU 3823 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.
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.
InputThe 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 <= 150OutputFor 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
题意:给出两个整数ab 使a+x b+x均为素数 且ab之间没有素数 求最小的符合条件的x
思路:java数组开大了就爆空间,注意空间;一个潜在条件a+x-(b+x)=a-b<150,即两个素数之差小于150;
代码:
import java.util.Scanner; public class Main { static final int max=(int)16000000; static int prime[]=new int[1031131]; static boolean is_prime[]=new boolean[max]; static int k=0; public static void Prime(){ is_prime[0]=is_prime[1]=true; for(int i=2;i<max;i++){ if(!is_prime[i]) prime[k++]=i; for(int j=0;j<k&&prime[j]*i<max;j++){ is_prime[i*prime[j]]=true; if(i%prime[j]==0) break; } } } public static void main(String[] args) { Prime(); // System.out.println(k); Scanner scan=new Scanner(System.in); int t=scan.nextInt(); for(int i=1;i<=t;i++){ int a=scan.nextInt(); int b=scan.nextInt(); if(a>b) { int tmp=a; a=b; b=tmp; } System.out.print("Case "+i+": "); boolean flag=false; int num=0; for(int j=0;j<k-1;j++){ if(prime[j]>=a && prime[j+1]>=b &&prime[j]-a==prime[j+1]-b &&prime[j+1]-prime[j]<150){ num=prime[j]-a; flag=true; break; } } if(flag) System.out.println(num); else System.out.println("-1"); } } }
以上是关于HDU 3823 Prime Friend(线性欧拉筛+打表)的主要内容,如果未能解决你的问题,请参考以下文章