Question

int j(int i) {
    if (i==0) return 2;
    return i*j(i-1);
}

calling j(4) gives 48.

I feel like I do understand the code, but don't know how 48 was achieved.

This is how I interpret it,

int j(4){

4 is not equal to 0 so it won't return 2

4*j(i-1) = 4*j(3)

then i go back to the top and repeat

3*j(2)
2*j(1)
1*j(0)

now i return 2.

This is where am lost, i'm not quite sure what to do after this step and how the answer to j(4) is 48.

Was it helpful?

Solution

The evaluation can be understood like this

j(4)
4 * j(3)
4 * (3 * j(2))
4 * (3 * (2 * j(1)))
4 * (3 * (2 * (1 * j(0))))   // When input to j is 0, returns 2
4 * (3 * (2 * (1 * 2)))
4 * (3 * (2 * 2))
4 * (3 * 4)
4 * 12
48

Till recursion reaches j(0), it goes deeper and deeper. But when it reaches it, it begins to unwind the recursion. And the most important thing is,

if (i==0) return 2;

is called the base condition of your recursion.

OTHER TIPS

j(0) clearly returns 2, right?

So j(1) returns 1*j(0), and j(0) is 2. So j(1) returns 2*1, or 2.

j(2) returns 2*j(1) or 2*2 or 4.

j(3) returns 3*j(2) or 3*4 or 12.

j(4) returns 4*j(3) or 4*12 or 48.

so this is calling

return 4 * 3 * 2 * 1 * 0 (no not 0 use 2)

result 48

You can trace through it:

j(4) = 4 * j(3) = 4 * (3 * j(2)) = 4 * 3 * 2 * j(1) 
     = 4 * 3 * 2 * 1 * j(0) = 4 * 3 * 2 * 1 * 2 = 48
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top