Ruby – Calculate Factorial Recursively

From: http://natashatherobot.com/recursion-factorials-fibonacci-ruby 

Solving Factorials Recursively

factorial is a non-negative integer, which is the product of all the positive integers less than or equal to itself. So, for example, the factorial of 5 is 120 (5 * 4 * 3 * 2 * 1). The factorial of 0 is always 1.

Without using recursion, we would calculate the factorial as follows in Ruby:

def factorial(n)
  (1..n).inject {|product, n| product * n }
end
 
puts factorial(5) # => 120

Now, here is the factorial method using recursion:

def factorial(n)
    if n == 0
        1
    else
        n * factorial(n-1)
    end
end
 
puts factorial(5) # => 120
 

So how does the recursive method work? I found it useful to draw it out…

Leave a Reply

Your email address will not be published. Required fields are marked *