I'm working on a ruby challenge and had to write a method that would calculate the Factorial of a number. I came across a solution below, but I don't understand how it works, specifically the section in the else statement:
def factorial(number)
if number <= 1
1
else
number * factorial(number - 1)
end
end
Lets say I run factorial(5) How is the else statement iterating through 5*4*3*2*1 in the number * factorial(number - 1) statement? I know this probably seems like it should be obvious, but it's not for me. Appreciate the help in advance.
This concept is known as recursion.
factorial(5) evaluates to
5 * factorial(4)
factorial(4) evaluates to
4 * factorial(3)
factorial(3) evaluates to
3 * factorial(2)
factorial(2) evaluates to
2 * factorial(1)
factorial(1) evaluates to 1 because 1 <= 1
Substituting values appropriately results in
5 * factorial(4)
5 * 4 * factorial(3)
5 * 4 * 3 * factorial(2)
5 * 4 * 3 * 2 * factorial(1)
5 * 4 * 3 * 2 * 1