r/learnjava • • Feb 08 '21

Help me understand recursion, please!

public static long method(long a, long b) {
    if (b == 0) {
        return b;
    }
    return a + method(a, b - 1);
}

So this apparently resolves to essentially a * b. I really don't understand this. The base case only ever returns b when b is zero, so in my flawed logic it's always a * 0 = 0.

51 Upvotes

15 comments sorted by

View all comments

0

u/dotJack Feb 08 '21

Im not sure you've checked what you've written.

It wouldn't return a * 0 because the method is a + 0.

But assuming you meant +.

Each method is replaced with another set of a + method() until b is zero, at which point the last of your stack of a + methods() would essentially be a + a + 0.

I think it would help you to write your logic out and write out what the end result of your recursive method would be, were you to write out the logic the program would construct.

If a was 3 and b was 3.

Your first iteration would be.

return 3 + (method(3,2)

your second recursion deconstruction would lead you to return 3 + 3 + method (3,1)

and then the final recursive deconstruction would be return 3 + 3 + 3 + 0 (here we return 0 instead of another method)

so if a is 3 and b is 3, then the result would be 9.

The reason it resolves to a * b, is because it adds a for b iterations.

Which is the same as saying a * b.

We add a together with a b-amount of iterations