0

I have the below recursive function to compute factorial of a number. The program works fine except when I remove the if condition. Can someone explain why?

This is the code that works fine --

public static long factUsingRecursion(int number) {
    if (number == 1) {
        return 1;
    } else {
        return number * factUsingRecursion(number - 1);
    }
}

Without the if condition (Code that throws the error),

public static long factUsingRecursion(int number) {
    return number * factUsingRecursion(number - 1);
}

I get the stack overflow error.

Exception in thread "main" java.lang.StackOverflowError at birst.FactorialUsingRecursion.factUsingRecursion(FactorialUsingRecursion.java:10)

Request experts to please advise me why this is the case?

4

7 に答える 7

2

次のように呼び出したときに何が起こるか想像してみてください。

factUsingRecursion(3);

次の場合:

3*factUsingRecursion(2)
3*2*factUsingRecursion(1)
3*2*1

if なし:

3*factUsingRecursion(2)
3*2*factUsingRecursion(1)
3*2*1*factUsingRecursion(0)
3*2*1*0*factUsingRecursion(-1)
3*2*1*0*-1*factUsingRecursion(-2)
3*2*1*0*-1*-2*factUsingRecursion(-3)
...
And so on... It will not stop until you encounter the StackOverflow error
于 2013-06-20T21:11:11.757 に答える
0

すべての整数 i に対して、i -1 で関数を呼び出しています。整数は無限であるため、関数の呼び出しを停止することはありません。例: -1000 は -1001 を呼び出します。これは、JVM のスタックにスペースがある限り続行されます。

于 2013-06-21T10:21:34.803 に答える