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

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

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
       prime();
    }

    /**
     * HJ60.查找组成一个偶数最接近的两个素数
     */
    private static void prime() {
        Scanner scanner = new Scanner(System.in);
        int num = scanner.nextInt();
        int value = num;
        Map<Integer, List<Integer>> map = new HashMap<>();
        for (int i = 1; i < num; i++) {
            if (!isPrime(i) || !isPrime(num - i)) {
                continue;
            }
            int tmp = Math.abs(i - (num - i));
            if (tmp < value) {
                value = tmp;
                map.put(value, Arrays.asList(i, num - i));
            }
        }
        List<Integer> lst = map.get(value);
        System.out.println(lst.get(0));
        System.out.println(lst.get(1));
    }

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


}

全部评论
把你的代码优化了一下
点赞 回复 分享
发布于 2023-08-30 15:29 上海

相关推荐

点赞 评论 收藏
分享
嵌入式的小白:有道理哈,这种就看能不能捞
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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