gpt4 book ai didi

java - 检查数组成员是否为素数时出错

转载 作者:行者123 更新时间:2023-12-02 09:10:19 25 4
gpt4 key购买 nike

我应该扫描一个整数数组,并循环遍历它,根据整数是否是素数打印“素数”或“非素数”。在某些情况下是正确的,而在其他情况下是错误的(例如 33)。这是我的代码:

public class Solution {

public static void main(String[] args) {
//Declaring the scanner
Scanner scan = new Scanner(System.in);

//Getting the number of integers to scan
int n = scan.nextInt();

//Declaring a numbers array
int[] numbers = new int[n];

//Scanning the integers
for(int i=0; i<n; i++)
numbers[i] = scan.nextInt();

//Determining if numbers are prime
for(int i=0; i<n; i++)
{
boolean isPrime = true;
for(int j=2; j<n; j++)
{
if(numbers[i] % j == 0){
isPrime = false;
System.out.println("Not prime");
break;
}
}
if(isPrime)
System.out.println("Prime");
}

}
}

最佳答案

您可以考虑的两个要点:

A. 您需要检查数字直至其平方根,即如果一个整数不能被 2 到其平方根之间的任何整数整除,则它是素数

B.您不需要额外的boolean标志(即代码中的isPrime)。

import java.util.Scanner;

public class Solution {

public static void main(String[] args) {
// Declaring the scanner
Scanner scan = new Scanner(System.in);

// Getting the number of integers to scan
System.out.print("How many numbers: ");
int n = scan.nextInt();

// Declaring a numbers array
int[] numbers = new int[n];

// Scanning the integers
for (int i = 0; i < n; i++) {
System.out.print("Enter number " + (i + 1) + ": ");
numbers[i] = scan.nextInt();
}

// Determining if numbers are prime
for (int i = 0; i < n; i++) {
int j, upperRange = (int) Math.sqrt(numbers[i]);
for (j = 2; j <= upperRange; j++)
if (numbers[i] % j == 0)
break;
if (numbers[i] != 1 && j > upperRange)
System.out.println(numbers[i] + " is Prime");
else
System.out.println(numbers[i] + " is not Prime");
}

}
}

示例运行:

How many numbers: 5
Enter number 1: 256
Enter number 2: 289
Enter number 3: 1
Enter number 4: 5
Enter number 5: 7
256 is not Prime
289 is not Prime
1 is not Prime
5 is Prime
7 is Prime

关于java - 检查数组成员是否为素数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59478722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com