题解 | #查找组成一个偶数最接近的两个素数#
查找组成一个偶数最接近的两个素数
https://www.nowcoder.com/practice/f8538f9ae3f1484fb137789dec6eedb9
import java.util.*; // 老八秘制小汉堡 public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()){ int i1 = scanner.nextInt(); ArrayList<Integer> su = new ArrayList<>(); for (int i = 0; i <i1; i++) { if (isPrime(i)){ su.add(i); } } LinkedHashMap<Integer, Integer> suhm= new LinkedHashMap<>(); for (int i = 0; i <su.size(); i++) { for (int j = 0; j <su.size(); j++) { if (su.get(i)+su.get(j)==i1&&suhm.get(su.get(i))==null){ suhm.put(su.get(i),su.get(j)); } } } LinkedHashMap<String, Integer> hm = new LinkedHashMap<>(); for(Integer key:suhm.keySet()){ String s = key + " " + suhm.get(key); hm.put(s,Math.abs(key-suhm.get(key))); } ArrayList<Integer> sort = new ArrayList<>(); for(String key:hm.keySet()){ sort.add(hm.get(key)); } Collections.sort(sort); for(String key:hm.keySet()){ if (hm.get(key)==sort.get(0)){ String[] split = key.split(" "); System.out.println(Math.min(Integer.valueOf(split[0]),Integer.valueOf(split[1]))); System.out.println(Math.max(Integer.valueOf(split[0]),Integer.valueOf(split[1]))); break; } } } } public static boolean isPrime(int n) { if (n <= 3) { return n > 1; } //判断一个数能否被小于sqrt(n)的数整除 int sqrt = (int)Math.sqrt(n); for (int i = 2; i <= sqrt; i++) { if(n % i == 0) { return false; } } return true; } }