I created two recursive methods for calculating factorial as follows:
private int fact1(int n) {
if (n == 0 || n == 1)
return 1;
return n * fact1(--n);
}
private int fact2(int n) {
if (n == 0 || n == 1)
return 1;
return fact2(--n) * n;
}
When I call fact1(4), it returns 24. When I call fact2(4), it returns 6( EDIT : not return 18, but 6). I know that the second method does 3 * 2 * 1, but I do not understand why not 4 * 3 * 2 * 1.
The same thing happens if I change the return to
return (n + 1) * fact3(--n);
return fact4(--n) * (n + 1);
Why does the method demonstrate this behavior?
Question about other behavior. I know that n * fact(n-1)is the best way to solve it.
Can someone help me understand the evaluation of this expression? Thank!
source
share