对于示例60,答案应该是2 2 3 5,但它只能得到2 3 5。
import java.util.Scanner;
public class PrimeFactor {
public static void main(String[] args) {
System.out.print("Enter a positive number: ");
Scanner scanner = new Scanner (System.in);
int number = scanner.nextInt();
int count;
for (int i = 2; i<=(number); i++) {
count = 0;
while (number % i == 0) {
number /= i;
count++;
}
if (count == 0) {
continue;
}
System.out.print(i + " ");
}
}
}
答案 0 :(得分:0)
问题在于,一旦发现60可以被2整除,它就会将它除以2(在这种情况下是两次)。
在System.out.print之后放置while语句的最后一个括号,它可以工作:
public static void main(String[] args) {
System.out.print("Enter a positive number: ");
Scanner scanner = new Scanner (System.in);
int number = scanner.nextInt();
int count;
for (int i = 2; i<=(number); i++) {
count = 0;
while (number % i == 0) {
number /= i;
count++;
if (count == 0) {
continue;
}
System.out.print(i + " ");
}
}
}
答案 1 :(得分:0)
如果你想采用不同的方式:
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.print("Enter a positive number: ");
Scanner scanner = new Scanner (System.in);
int number = scanner.nextInt();
int divisor = 2;
while(number != 1) {
if(number % divisor == 0) {
System.out.println(divisor + " ");
number /= divisor;
}
else {
divisor++;
}
}
}
}