检查给定的数字是否为素数?

Check whether the given number is prime or not?

我正在尝试实现一个代码来检查给定的数字数组是否为质数,

但是当数字不是素数时,输出会显示“素数”和“非素数”两个答案。我在这里犯了什么错误,很高兴得到您的答复?提前致谢!

这是我的代码。

    Scanner scan = new Scanner(System.in);
    int number = scan.nextInt();
    int[] arr = new int[number];
    for (int i = 0; i < number; i++) {
        arr[i] = scan.nextInt();

    }

    for (int i = 0; i < number; i++) {
        int num = arr[i];
        for (int j = 2; j <= Math.sqrt(num); j++) {
            if (num % j == 0 && num !=2) {
                System.out.println(num + "Not prime");
                break;
            }
        }
        System.out.println(num +"Prime");
    }

你应该记得这个数是不是素数。您的代码没有这样做,所以两个打印件都已到达。

Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
int[] arr = new int[number];
for (int i = 0; i < number; i++) {
    arr[i] = scan.nextInt();

}

for (int i = 0; i < number; i++) {
    int num = arr[i];
    boolean isPrime = true;

    for (int j = 2; j <= Math.sqrt(num); j++) {
        if (num % j == 0 && num !=2) {
            isPrime = false;
            break;
        }
    }

    if (isPrime) {
        System.out.println(num +"Prime");
    } else {
        System.out.println(num + "Not prime");
    }

}

使用布尔值来跟踪数字是否为质数。假设它一开始是真的(质数),如果发现它不是质数就设置它为假。

boolean isPrime = true;

然后,根据该布尔值确定消息。

String message = isPrime ? "Prime" : "Not prime";

你可以通过引入一个布尔变量来修复它:

    for (int i = 0; i < number; i++) {
        int num = arr[i];
        boolean isPrime = true;
        for (int j = 2; j <= Math.sqrt(num); j++) {
            if (num % j == 0 && num !=2) {
                isPrime = false;
                break;
            }
        }
        if (isPrime) {
           System.out.println(num +"Prime");
        } else {
           System.out.println(num + "Not prime");
        } 
    }

如果您有兴趣让您的代码更高效一点,您可以走这条路。

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
        15, 16, 17, 18, 19, 20 };
for (int num : numbers) {
    System.out.println(num + ((isPrime(num) ? " is" : " is not") + " a prime"));
}       

private static boolean isPrime(int num) {
    // two is a prime
    if (num == 2) {
       return true;
    }
    // numbers 1 or less or any even 
    // number (sans 2) are not primes
    if (num <= 1 || num % 2 == 0) {
        return false;
    }
    // Now you can check for odd divisors.
    // and increment by 2 starting with 3.
    for (int i = 3; i <= Math.sqrt(num); i+=2) {
        if (num % i == 0) {
            return false;
        }
    }
    return true;
}