使用递归方法获取因子

Getting factors using recursive method

输出是正确的,但它不时地在因子的末尾显示 -1(无限循环)。我知道递归方法中的 while 循环有问题,但我不知道它是什么。得到最终答案后如何停止递归调用?我应该使用什么来代替 while 循环?

public static void main() {
    int num;
    System.out.print("\fInput:");
    num = kb.nextInt();
    int temp = 1;
    factors(num, temp);
}

public static void factors(int num, int temp) {
    int count = 2;

    while (temp != num) {
        if ((num % count) == 0) {
            System.out.print(count + " * ");
            factors(num / count, temp * count);
        } else
            count++;
    }
}

你的停止条件 (temp!=num) 永远不会为假。 当你得到最后一个因子并且你想停止时,你将调用 factors(1, "the original number"),因此 while 循环将继续。

你应该试试:

while (num != 1)

不需要临时参数。

首先,这里不需要递归。如果您使用递归,您将始终从 count = 2 开始新的,即使您已经检查了更大的值。

所以,而不是

factors(num/count, temp*count);

我会用

num = num/count;

其次,正如 Attila 所说,您不需要 temp 参数,真正需要检查的是 num != 1 是否为真。

如果你真的想使用递归,会有更好的方法:将方法 factors 传递给计数器,这样你就不必总是从 2 开始。在这种情况下,你不需要不需要任何循环:

public static void main()
{
    int num;
    System.out.print("\fInput:");
    num=kb.nextInt();
    int count=2;
    factors(num, count);

}



public static void factors(int num, int count)
{  
    if (num == 1)
        return;

    if((num%count)==0)
    {
        System.out.print(count+ " * ");
        factors(num/count, count);
    }
    else 
        factors(num,count+1);
    }
}

正如其他人指出的那样,while (temp!=num) 永远不会是 false,程序将继续无限循环。 Karl_Costa 的解决方案效果很好,但是,您仍然可以使用 while 循环进行计数,如图所示。正如其他人指出的那样,没有必要使用 temp.

这是另一个可行的解决方案-

public static void main() {
    int num;
    System.out.print("\fInput:");
    num=kb.nextInt();
    System.out.print("1");  // To always print 1 as a factor.
    factors(num, 2);
}

public static void factors(int num, int count) {
    while(num%count != 0 && num>count) {
        count++;
    }
    System.out.print(" * " + count);
    if(num==count) {
        return;
    }
    if(num%count==0)
        factors(num/count, count);
    else {
        factors(num/count, count+1);
    }
}
class RecursiveFactors
{
    static void factors(int a, int n)
    {
        if(n%a == 0)
        {
            System.out.println(a);
        }    

        if(a<=n)
            factors(a+1, n);
    }    

    public static void main(String args[])
    {
        factors(1,25);
    }
}