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.
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
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.
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;
n--;
}
return f;
}
factorial(7) // <- 5040
When memory is a concern, something like the above is preferred since it uses very little of it.