gpt4 book ai didi

java - 从数组中找出所有质数

转载 作者:行者123 更新时间:2023-12-01 11:34:25 25 4
gpt4 key购买 nike

我想创建一个程序,要求用户使用数组输入 5 个整数,并确定输入的所有素数。但我对此有困难。似乎有什么问题?我为此使用 JCreator。

import java.util.Scanner;
public class PrimeNumbers{
public static void main (String[] args){
int[] array = new int [5];
Scanner in = new Scanner (System.in);

System.out.println("Enter the elements of the array: ");
for(int i=0; i<5; i++)
{
array[i] = in.nextInt();
}
//loop through the numbers one by one
for(int i=0; i<array.length; i++){
boolean isPrime = true;

//check to see if the numbers are prime
for (int j=2; j<array[i]; j++){

if(array[i]%j==0){
isPrime = false;
break;
}
}
//print the number
if(isPrime)

System.out.println(array[i] + " are the prime numbers in the array ");
}
}
}

最佳答案

您正在检查循环计数器,而不是数组中的值。尝试类似的事情

for (int j=2; j<array[i]; j++){
if(array[I]%j==0){
isPrime = false;
break;
}

我还没有测试过这个。

更新

要打印结果,可以在找到每个结果时将其打印出来,或者将质数复制到输出数组中,然后在完成检查后打印该结果。详细信息取决于您使用的语言。

请注意,您没有使用非常有效的检测算法; Google 寻求更好的解决方案。

关于java - 从数组中找出所有质数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30150251/

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