题解 | #查找组成一个偶数最接近的两个素数#--素数&哈希

查找组成一个偶数最接近的两个素数

https://www.nowcoder.com/practice/f8538f9ae3f1484fb137789dec6eedb9

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 1; i < num; i++) {
            if (isPrime(i)) {
                int other = num - i;
                if (isPrime(other)) {
                    map.put(Integer.max(i, other) - Integer.min(i, other), Integer.min(i, other));
                }
            }
        }
        // 找到最小差值
        Collection<Integer> keys = map.keySet();
        int min = Collections.min(keys);
        // 排序
        int one = map.get(min);
        int other = num - one;
        System.out.println(Integer.min(one, other));
        System.out.println(Integer.max(one, other));
    }

    private static boolean isPrime(int num) {
        if (num <= 2) {
            return true;
        }
        int sqrt = (int) Math.sqrt(num);
        for (int i = 2; i <= sqrt; i++) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务