Understanding Java Behavior in Recursive Factorial

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

//fact3(4) returns 60.
return (n + 1) * fact3(--n); // wrong
//fact4(4) returns 24
return fact4(--n) * (n + 1); // works

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!

+4
source share
1 answer

:

return n * f(--n);

return f(--n) * n;

n = 4, :

return 4 * f(3);

return f(3) * 3;

--n , n 1. --.

. :

// first
return 4 * f(3);
return 4 * 3 * f(2);
return 4 * 3 * 2 * f(1);
return 4 * 3 * 2 * 1;

// second
return f(3) * 3;
return f(2) * 2 * 3;
return f(1) * 1 * 2 * 3;
return 1 * 1 * 2 * 3;

, :

return f(n--) * n;

:

return f(4) * 3;

postfix --: n f(...) -1.

+8

Source: https://habr.com/ru/post/1659772/


All Articles