我写了这段代码来确定两个数字之间哪些数字是某些类型是素数,哪些是复合数。用户键入两个数字,例如5& 10,在这种情况下程序应该输出:
5是素数 6不是素数 7是素数 8不是素数 9不是素数 10不是素数
但它没有正确地做到这一点。例如,如果用户输入13和33,则输出是13,14和15是素数,但所有其他数字都不是。更奇怪的是,结果相互矛盾。例如,如果用户输入10和20,则程序输出所有数字都不是素数。
package more.basic.applications;
import java.util.Scanner;
public class MoreBasicApplications {
public static void main(String[] args)
{
//program to determine how many numbers between 2 numbers inclusive are prime, and how many are composite, as well as display them
int j = 2;
Scanner reader = new Scanner(System.in);
System.out.println("Please enter number 1, between 0 and 100: ");
int number = reader.nextInt();
boolean composite = false;
System.out.println("Please enter number 2, between 0 and 200: ");
int number2 = reader.nextInt();
int difference = number2 - number;
int[] array = new int[difference+1];
for (int i = 0; i < array.length; i++)
{
array[i] = number + i;
while (j <= Math.sqrt(array[i]))
{
if (array[i]%j == 0) {
composite = true;
}
j++;
}
if (composite == true) {
System.out.println (array[i] + " is not prime.");
}
else
{
System.out.println (array[i] + " is prime.");
}
}
}
答案 0 :(得分:1)
看起来你没有在j
循环开始时将for
“重置”回2,所以j
会越来越大。
for (int i = 0; i < array.length; i++) {
j = 2; // reset j back to 2.
array[i] = number + i;
while (j <= Math.sqrt(array[i])) {
if (array[i]%j == 0) {
composite = true;
}
j++;
}
if (composite == true) {
System.out.println (array[i] + " is not prime.")
} else {
System.out.println (array[i] + " is prime.");
}
}