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

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

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


public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int n = sc.nextInt();
            int num1 = getResult(n);
            System.out.println(num1);
            System.out.println(n - num1);
        }
    }

    private static int getResult(int n) {
        int i = n/2;
        int j = n - i;
        while(!isPrim(i) || !isPrim(j)){
            i--;
            j++;
        }
        return i;
    }

    private static boolean isPrim(int i) {
        if(i == 1){
            return false;
        }
        for(int j = 2; j * j <= i;j++){
            if(i % j ==0){
                return false;
            }
        }
        return true;
    }
}
全部评论

相关推荐

评论
点赞
2
分享

创作者周榜

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