问题及代码:
问题描述:
输入一个数,计算并输出这个数所有的质因数。例如 输入120,输出2 2 2 3 5
程序代码:
public class Exercise4_16 {
// Main method
public static void main(String args[]) {
java.util.Scanner input = new java.util.Scanner(System.in);
// Prompt the user to enter a positive integer
System.out.print(
"Enter a positive integer: ");
int number = input.nextInt();
// Find all the smallest factors of the integer
System.out.println("The factors for " + number + " is");
int factor = 2;
while (factor <= number) {
if (number % factor == 0) {
number = number / factor;
System.out.println(factor);
}
else {
factor++;
}
}
}
}
运行结果: