题解 | #查找组成一个偶数最接近的两个素数#
查找组成一个偶数最接近的两个素数
https://www.nowcoder.com/practice/f8538f9ae3f1484fb137789dec6eedb9
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); // 输入 int num = Integer.parseInt(str); TreeMap<Integer, String> treeMap = new TreeMap<>(); for (int i = 1; i <= num / 2; i++) { // 如果素数 if (judgeIsNum(i)) { int j = num - i; // 判断另外一个是不是素数 if (judgeIsNum(j)) { int result = j - i; treeMap.put(result, i + "," + j); } continue; } } // 遍历结果,获取第一个最小值就可以 Set<Integer> set = treeMap.keySet(); for (Integer key : set) { String res = treeMap.get(key); String[] split = res.split(","); for (int i = 0; i < split.length; i++) { System.out.println(split[i]); } break; } } // 判断一个数是否是素数 public static boolean judgeIsNum(Integer integer) { if (integer == 1 || integer == 2 || integer == 3) { return true; } for (int i = 2; i < integer; i++) { if (integer % i == 0) { return false; } } return true; } }