ruby - How is this method solving my factorial? -



ruby - How is this method solving my factorial? -

i'm working on ruby challenge , had write method calculate factorial of number. came across solution below, don't understand how works, section in else statement:

def factorial(number) if number <= 1 1 else number * factorial(number - 1) end end

lets run factorial(5) how else statement iterating through 5*4*3*2*1 in number * factorial(number - 1) statement? know seems should obvious, it's not me. appreciate help in advance.

this concept known 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 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

ruby factorial

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -