我在编程类中完成这个因子生成器时遇到了一些麻烦。它应该采用一个数字,并使用nextFactor方法打印出所有因子。当我将数字设置为因子而不是150时,它打印出“1 2 3 5”,它应该打印“2 3 5 5”。那么,我应该从哪里开始呢?我看过Java - Factor Generator program nextfactor method,但它没有发现我的任何查询
public class FactorGenerator
{
//user inputs int from scanner in FactorTester class
public FactorGenerator(int i)
{
num = i;
}
//Checks to see if num can be factored, but does not factor it.
//Goes through all possible factors of num and returns true if the remainder == 0
public boolean hasMoreFactors()
{
for(int i = 1; i < num; i++)
{
//check if the remainder is anything other then 0
if(num % i == 0)
{
return true;
}
}
return false;
}
//Actually factors num and prints out the factor at the end of every loop.
public void nextFactor()
{
for(int i = 1; i < num; i++)
{
//check if the remainder is anything other then 0
if(num % i == 0)
{
System.out.println(i);
num /= i;
}
}
System.out.println("Done.");
}
private int num;
}
答案 0 :(得分:1)
尝试这些因素可以重复,因此您需要循环,直到您提取了该因子的所有实例
public void nextFactor()
{
for(int i = 2; i <= num; i++)
{
//check if the remainder is anything other then 0
while (num >= i && num % i == 0)
{
System.out.println(i);
num /= i;
}
}
System.out.println("Done.");
}
另一种方法是在循环体中进行增量
public void nextFactor()
{
for(int i = 2; i <= num;)
{
//check if the remainder is anything other then 0
if (num % i == 0)
{
System.out.println(i);
num /= i;
} else {
i++;
}
}
System.out.println("Done.");
}
答案 1 :(得分:0)
首先,它将始终打印出1,因为任何整数/ 1将始终具有零余数。如果你想跳过1,你可以从你的2开始,而不是1。
我建议这样的事情:(注意这部分基于BevynQ的答案):
for(int i = 2; i <= num; i++){
while (num >= i && num % i == 0) {
System.out.println(i);
num /= i;
}
}