题解 | #查找组成一个偶数最接近的两个素数#
查找组成一个偶数最接近的两个素数
https://www.nowcoder.com/practice/f8538f9ae3f1484fb137789dec6eedb9
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
int tar = scanner.nextInt();
ArrayList<Integer> list = new ArrayList<>();
for (int i = 1; i < tar; i++) {
int count = calSu(i);
if (count <= 2) {
list.add(i);
}
}
LinkedHashMap<Integer, Integer> objectObjectHashMap = new LinkedHashMap<>();
for (int i = 0; i <= list.size() - 1; i++) {
int result = tar - list.get(i);
if (list.indexOf(result) != -1) {
int cha = result - list.get(i);
if (cha >= 0) {
objectObjectHashMap.put(list.get(i), cha);
}
}
}
System.out.println(getTail(objectObjectHashMap).getKey());
System.out.println(tar - getTail(objectObjectHashMap).getKey());
}
}
public static <K, V> Map.Entry<K, V> getTail(LinkedHashMap<K, V> map) {
Iterator<Map.Entry<K, V>> iterator = map.entrySet().iterator();
Map.Entry<K, V> tail = null;
while (iterator.hasNext()) {
tail = iterator.next();
}
return tail;
}
public static int calSu(int tar) {
int count = 0;
for (int i = 1; i <= tar; i++) {
if (tar % i == 0) {
count++;
}
}
return count;
}
}
查看1道真题和解析