public class Exercise {
public static void main(String[] args) {
int integer;
int num = 2;//a number to be tested for primeness
int count = 0;//count the number of prime numbers
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a number");
integer = keyboard.nextInt();
while (count <= integer) {
boolean isPrime = true;//is current number prime
//test wether number is prime
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {//if true number is not prime
isPrime = false;//set is prime to false
break;//exit the loop
}
}
if (isPrime) {
count++;
System.out.print(num);
}
num++;
}
}
}
嗨我需要这个程序只打印一个整数的最小因子,例如,如果输入为60,则输出为2,3,5。它确实如此,但它也增加了许多其他提升的素因子。有什么建议?感谢
答案 0 :(得分:3)
你的循环条件是打印首先&#39; x&#39;素数因此,如果输入60,它将打印前60个素数。那是2,3,5,7,11 ......
请修改这样的代码以获得所需的输出(只需替换整个循环)
while (num <= integer) { //Changed the condition here to
//stop when the number reached integer and not count
boolean isPrime = true;//is current number prime
//test wether number is prime
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {//if true number is not prime
isPrime = false;//set is prime to false
break;//exit the loop
}
}
if (isPrime && integer % num == 0) {// added an additional check that
// print the number only if it is prime and
// it is divides the integer with an remainder of 0
System.out.println(num);
}
num++;
}
输入60,您将输出为
2 3 5
请注意,您不再需要计算变量