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

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

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);
        scanner.useDelimiter("\n");

        while (scanner.hasNextInt()) {
            int num = scanner.nextInt();
            HashMap<Integer, Integer> hashMap = new HashMap<>();
            int[] res = new int[2];
            int min = num;
            for (int i = 2; i < num; i++) {
                if (is(i) && is(num - i)) {
                    if (Math.abs(num - i - i) < min) {
                        min = Math.abs(num - i - i);
                        res[0] = i;
                        res[1] = num - i;
                    }
                }
            }
            Arrays.stream(res).sorted().forEach(System.out::println);
        }
    }

    public static boolean is(int i) {
        for (int j = 2; j <= Math.sqrt(i); j++) {
             if (i%j==0) {
                 return false;
             }
        }
        return true;
    }
}

全部评论

相关推荐

03-19 17:49
运营
牛客327038019号:你把那贼低的gpa写上去干嘛
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务