因此,对于我的作业,我必须编写一个程序,要求用户输入一个整数,然后打印出该数字的素因数分解。 这是我的:
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.println(i+ "**" + count);
}
}
}
我现在遇到的问题是,每当我用数字 15453 运行它时,我都会得到从 1 到 100 的每个因子及其指数的列表,而我只需要素因子,我就卡住了至于如何进行。
最佳答案
你快到了!将 if-continue
block 移到 for
循环之外。否则,它会“继续”最内层的循环,而不是您想要的循环。
while (number % i == 0) {
number /= i;
count++;
}
if (count == 0) {
continue;
}
System.out.println(i+ "**" + count);
或者,您可以将 System.out.println
调用包含在 if (count != 0)
中,因为它是 continue< 之后的唯一语句
:
while (number % i == 0) {
number /= i;
count++;
}
if (count != 0) {
System.out.println(i+ "**" + count);
}
你在ideone上的程序:link .
关于Java 显示一个数的质因数分解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12570099/