题解 | #密码验证合格程序#

素数伴侣

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

import java.util.; import java.lang.;

// 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 int count = 0; while (in.hasNextLine()) { String read = in.nextLine(); String[] temps = null; if (!read.contains(" ")) { // 长度 count = Integer.parseInt(read); } read = in.nextLine(); if (read.contains(" ")) { temps = read.split(" "); } int voi = 0; int[] used = new int[count]; // 使用过了的,不能用 for (int a = 0; a < temps.length; a++) { if (used[a] == 1) { continue; } for (int b = a + 1; b < temps.length; b++) { if (used[b] == 1) { continue; } int value = Integer.parseInt(temps[a]) + Integer.parseInt(temps[b]); if (isPrime(value)) { used[a] = 1; used[b] = 1; voi++; break; } } } System.out.println(voi); } in.close(); }

public static boolean isPrime(int n) {
    if (n <= 3) {
        return n > 1;
    }
    int start = 2;
    while (true) {
        if (n % start == 0) {
            if (n != start) {
                return false;
            } else {
                return true;
            }
        } else {
            start++;
        }
    }
}

}

全部评论

相关推荐

投递美团等公司10个岗位
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务