华为OJ平台——查找组成一个偶数最接近的两个素数

 1 import java.util.Scanner;
 2 
 3 /**
 4  * 问题描述:任意一个偶数(大于2)都可以由2个素数组成,组成偶数的2个素数有很多种情况,
 5  * 本题目要求输出组成指定偶数的两个素数差值最小的素数对,其中 5 < n <= 10000
 6  * eg:输入20,输出7  13
 7  */
 8 public class PrimePair {
 9     
10     public static void main(String[] args) {
11         Scanner cin = new Scanner(System.in) ;        
12         int n = cin.nextInt() ;
13         cin.close();
14         //简单判断输入的范围
15         if(n%2 == 1 || n <= 5 || n > 10000){
16             System.exit(-1);; ;
17         }        
18         findPrimePair(n) ;        
19 
20     }
21 
22     /**
23      * 找出满足条件的素数对
24      * @param n
25      */
26     private static void findPrimePair(int n) {
27         for(int i = n/2-1 ; i > 0 ; i -= 2){
28             if(judgePrime(i) && judgePrime(n-i)){
29                 System.out.println(i) ;
30                 System.out.println(n-i) ;
31                 return ;
32             }
33         }            
34     }
35 
36     /**
37      * 判断一个整数是否是素数
38      * @param x
39      * @return true---素数   false---不是
40      */
41     private static boolean judgePrime(int x) {
42         double end = x/2 ;
43         if (x == 1) {
44             return true;
45         } else {
46             for (int i = 2; i <= end; i++) {
47                 if (x % i == 0) {
48                     return false;
49                 }
50                 end = x / (i + 1.0);
51             }
52             return true;
53         }
54     }
55 }
原文地址:https://www.cnblogs.com/mukekeheart/p/5592318.html