Java显示数字的Prime Factorization [英] Java Display the Prime Factorization of a number
问题描述
因此,对于我的任务,我必须编写一个程序,要求用户输入整数输入,然后打印出该数字的素数因子分解。
这就是我所拥有的:
So for my assignment, I have to write a program that asks the user for an integer input and then print out that number's prime factorization. This is what I have:
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的每个因子的列表及其指数,当我只想要素因子时,我就不知道如何继续。
The problem I have right now is that whenever I run it with, like, the number 15453, I get a list of every factor from 1 to 100 and its exponent when I only want the prime factors, and I'm stuck as to how to proceed.
推荐答案
你快到了!将 if-continue
块移到以外的
循环中。否则,它继续最内圈,而不是你想要的那个。
You are almost there! Move the if-continue
block outside the for
loop. Otherwise, it "continues" the inner-most loop, rather than the one you intended.
while (number % i == 0) {
number /= i;
count++;
}
if (count == 0) {
continue;
}
System.out.println(i+ "**" + count);
或者,您可以附上 System.out.println
调用 if(count!= 0)
,因为它是之后的唯一语句
:
Alternatively, you could enclose the System.out.println
call in if (count != 0)
, because it's the only statement following the continue
:
while (number % i == 0) {
number /= i;
count++;
}
if (count != 0) {
System.out.println(i+ "**" + count);
}
您在ideone上的程序:链接。
Your program on ideone: link.
这篇关于Java显示数字的Prime Factorization的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!