I am new to recursive and I'm having trouble understanding how this recursive factorial function is calculated.
When I try to run through the code with my mind, this is how I visualize it:
If number = 4,
1st return: 4 x 3
2nd return: 3 x 2
3rd return: 2 x 1
So in my mind it is (4 x 3) * (3 x 2) * (2 x 1) but obviously the right return would be 4 X 3 X 2 X 1 instead. I want to be able to understand how does it get 4 X 3 X 2 X 1.
public static long factorial(long number) {
if (number <= 1)
return 1;
else
{
System.out.println(number + " x " + (number-1) );
return number * factorial(number - 1);
}
}
Any help and explanation would be greatly appreciated.
Your visualization should be:
If number = 4,
1st return: 4 x (2nd return)
2nd return: 3 x (3rd return)
3rd return: 2 x (4th return)
4th return: 1
That then simplifies to 4 x 3 x 2 x 1, as expected.
Basically, you need to differentiate between "return value x" and "return the result of recursing, passing in value x".
See more on this question at Stackoverflow