Understanding operations with returning a method!


public int multiplyEvens(int n) {
    if(n <= 0)
        throw new IllegalArgumentException();

    if(n == 1)
        return 2;

return 2 * n * multiplyEvens(n-1);

What does this mean exactly? I keep getting mixed thoughts. But I’m understanding that this returns the method before the multiplication is attempted. I need help. What does this do?
This is entire code.


That is an example of recursion. There appears to be some missing code, though, namely the base case.

What exercise is this from (link to lesson, please)?


These are just examples given by a university site.
So what does this recursion actually do. I’ve been doing math in my head for the past hour… and nothing solid has come of it


Okay, we can see there is a base case present:

   if (n == 1) {
       return 2;

Suppose the input value is 7. In a recursive function there is what we refer to as a call stack that holds on to return expressions until the base case is reached and the stack is wound down. This is necessary because each return except the base case depends on the return value of a previous call.

Stack in case n == 7

return 2 * 7 * multiplyEvens(6)
return 2 * 6 * multiplyEvens(5)
return 2 * 5 * multiplyEvens(4)
return 2 * 4 * multiplyEvens(3)
return 2 * 3 * multiplyEvens(2)
return 2 * 2 * multiplyEvens(1)
return 2
multiplyEvens(7)  // <- 645120

Notice how the function calls itself with a reduced value each time. This is necessary to keep from creating an infinite loop that will overflow the stack eventually when memory runs out.


I understand the repetition of sorts. I think its just me not knowing how to do factorials properly lol.
I got it now though. I was trying to sort out the numbers in an additive way rather than using factorials based on factored numbers


There are other ways of doing it that do not involve recursion. However your professor is likely to hand you lots recursive function problems so you get a full grasp, eventually, of how they work and how to write them. It’s an important skill to acquire, especially at the more advanced level.

Consider this JavaScript non-recursive function for calculating factorials…

function factorial(n) {
    f = 1;
    while (n > 1) {
        f *= n;
    return f;
factorial(7)    // <- 5040

When memory is a concern, something like the above is preferred since it uses very little of it.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.