题解 |HJ60 #查找组成一个偶数最接近的两个素数#
查找组成一个偶数最接近的两个素数
https://www.nowcoder.com/practice/f8538f9ae3f1484fb137789dec6eedb9
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { // 任意一个偶数(大于2)都可以由2个素数组成,组成偶数的2个素数有很多种情况,本题目要求输出组成指定偶数的两个素数差值最小的素数对。 // 数据范围:输入的数据满足 4≤n≤1000 Scanner scanner = new Scanner(System.in); int nextInt = scanner.nextInt(); int initNum = 1; //偶数减去一个素数就是它的素数对中另一个素数 int otherNum = 0; Map<Integer, Integer> map = new HashMap<>(); ArrayList<Integer> list = new ArrayList<>(); // System.out.println(IsprimeNum(nextInt)); if (4 <= nextInt && nextInt <= 1000) { //是偶数 if (nextInt % 2 == 0) { while (initNum < nextInt) { otherNum = nextInt - initNum; if (IsprimeNum(initNum) && IsprimeNum(otherNum)) { int result = Math.abs(otherNum - initNum); list.add(result); //(initNum,otherNum)即素数对子 //map中存的就是素数对子的差以及其中一个素数 map.put(result, initNum); } initNum++; } //得到list素数对子的差的最小值 Integer min = Collections.min(list); //去匹配map中的key Set<Map.Entry<Integer, Integer>> entrySet = map.entrySet(); for (Map.Entry<Integer, Integer> entry : entrySet) { if (entry.getKey().equals(min)) { int other = nextInt - entry.getValue(); if (other < entry.getValue()) { System.out.println(other); System.out.println(entry.getValue()); } else { System.out.println(entry.getValue()); System.out.println(other); } } } } } } //判定是否是素数 public static boolean IsprimeNum(int i) { ArrayList<Integer> list = new ArrayList<>(); int flag = 1; while (flag <= i) { if (i % flag == 0) { list.add(flag); } flag++; } if (list.size() == 2) { return true; } else { return false; } } }