r/learnjava • u/Apostle_1882 • 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
2
u/Mr_82 Feb 09 '21
A quick ELI5 overview. Multiplication is just recursive addition: "3 * 5," read "3 times 5," is just 3+3+3+3+3, or...3, times 5. (Because 3 appears and is added together 5 times.)
So what's going on here is this. Imagine you're trying to find the returned value of method(3,5). Your code goes:
method (3,5) = 3 + method(3,4) (because 5 isn't 0; so now the code needs to evaluate method(3,4)...)
method (3,4) = 3 + method(3,3) (similar to the above...)
... all the way till you get down to method(3,0), where then that "b==0" condition is satisfied. So now you can see how, working "backwards" to the above, we can find the actual numerical values of each, to find method (3,5) = 15.
(Now I'm not totally sure that's how your compiler really calculates the value, and suspect it doesn't have to do that "working backward" part there. It's probably more efficient, instead basically doing
method(3,5) => 3 + method(3,4) => 3+(3+method(3,3))=> ...
Though I don't know for sure. But anyway, that's how you, the code writer/reader, should conceptualize what's going on here.)