这是一个确定10个数字数组中的元素是否为质数的程序。素数将被-1替换,其他则在打印时保持不变。
对我来说似乎很好,但是当我用9s运行代码时,有些将得到-1,这意味着9是素数(错误),有些则返回9(不是素数)。我为什么要遇到这个?有人可以帮忙吗
import java.util.Scanner;
public class Question5{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] array = new int [10];
for (int i = 0; i < array.length; i++){
System.out.println("Enter your number " + i);
array[i] = input.nextInt();
}
System.out.println("Before method: ");
for (int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
}
System.out.println();
prime(array);
System.out.println("After the method: ");
for (int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
}
System.out.println();
}
public static void prime(int[] list){
boolean isPrime = true;
int count = 0;
for (int i = 0; i < list.length; i++){
isPrime = true;
for (int j = 2; j < i; j++){
count = i;
if (list[i] % j == 0){
isPrime = false;
break;
}
if (list [i] == 0 || list[i] == 1){
isPrime = false;
break;
}
if (list [i] == 2){
isPrime = true;
list[count] = -1;
}
}
if (isPrime){
list[count] = -1;
}
}
}
}
答案 0 :(得分:1)
立即引起我注意的主要逻辑问题是您没有正确检查素数。您应该从2循环遍历直到数组中的特定数字,并检查除数。相反,您从2进行迭代,直到列表的长度。试试这个版本:
public static void prime(int[] list) {
for (int i=0; i < list.length; ++i) {
int num = list[i];
boolean isPrime;
if (num == 1) {
isPrime = false;
}
else {
isPrime = true;
}
for (int j=2; j <= Math.sqrt(num); ++j) {
if (num % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
list[i] = -1;
}
}
return;
}
public static void main(String args[]) {
int[] list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
prime(list);
System.out.println(Arrays.toString(list));
}
上面打印的main()
:
[1, -1, -1, 4, -1, 6, -1, 8, 9, 10]
答案 1 :(得分:1)
您有三个错误:
j < list[i]
或j *j <= list[i]
0
和1
标识为素数,这是不正确的。您应该在内部循环之前测试if (list [i] == 0 || list[i] == 1)
。代码应如下所示:
public static void prime(int[] list){
boolean isPrime = true;
int count = 0;
for (int i = 0; i < list.length; i++){
isPrime = true;
if (i < 2) {
isPrime = false;
} else {
for (int j = 2; j * j <= list[i]; j++){
count = i;
if (list[i] % j == 0){
isPrime = false;
break;
}
if (list [i] == 2){
isPrime = true;
list[i] = -1;
}
}
}
if (isPrime){
list[i] = -1;
}
}
}
例如:
Enter your number 0
0
Enter your number 1
1
Enter your number 2
2
Enter your number 3
3
Enter your number 4
4
Enter your number 5
5
Enter your number 6
6
Enter your number 7
7
Enter your number 8
8
Enter your number 9
9
Before method:
0 1 2 3 4 5 6 7 8 9
After the method:
0 1 -1 -1 4 -1 6 -1 8 9