gpt4 book ai didi

java - 因子生成器出现问题

转载 作者:行者123 更新时间:2023-12-01 13:45:42 26 4
gpt4 key购买 nike

我在完成编程课上的这个因子生成器时遇到了一些麻烦。它应该接受一个数字,并使用 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;
}

最佳答案

尝试这个因素可以重复,因此您需要循环,直到提取该因素的所有实例

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.");
}

关于java - 因子生成器出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20390985/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com