0
0
RubyProgramBeginner · 2 min read

Ruby Program to Find Factorial Using Recursion

You can find the factorial of a number in Ruby using recursion by defining a method like def factorial(n); return 1 if n <= 1; n * factorial(n - 1); end which calls itself until it reaches 1.
📋

Examples

Input0
Output1
Input5
Output120
Input1
Output1
🧠

How to Think About It

To find the factorial using recursion, think of the problem as multiplying the number by the factorial of the number just before it. Keep doing this until you reach 1, which is the base case where you stop the recursion.
📐

Algorithm

1
Get the input number n
2
If n is less than or equal to 1, return 1 as factorial of 0 or 1 is 1
3
Otherwise, multiply n by the factorial of n minus 1
4
Return the result
💻

Code

ruby
def factorial(n)
  return 1 if n <= 1
  n * factorial(n - 1)
end

puts factorial(5)
Output
120
🔍

Dry Run

Let's trace factorial(5) through the code

1

Call factorial(5)

Since 5 > 1, calculate 5 * factorial(4)

2

Call factorial(4)

Since 4 > 1, calculate 4 * factorial(3)

3

Call factorial(3)

Since 3 > 1, calculate 3 * factorial(2)

4

Call factorial(2)

Since 2 > 1, calculate 2 * factorial(1)

5

Call factorial(1)

Since 1 <= 1, return 1

6

Return values back up

factorial(2) = 2 * 1 = 2 factorial(3) = 3 * 2 = 6 factorial(4) = 4 * 6 = 24 factorial(5) = 5 * 24 = 120

CallReturn Value
factorial(1)1
factorial(2)2
factorial(3)6
factorial(4)24
factorial(5)120
💡

Why This Works

Step 1: Base Case

The code stops recursion when n <= 1 because factorial of 0 or 1 is 1, preventing infinite calls.

Step 2: Recursive Call

For numbers greater than 1, the function calls itself with n - 1, breaking the problem into smaller parts.

Step 3: Multiplying Results

Each call multiplies the current number n by the factorial of n - 1, building up the final factorial value.

🔄

Alternative Approaches

Iterative approach
ruby
def factorial(n)
  result = 1
  (2..n).each { |i| result *= i }
  result
end

puts factorial(5)
This uses a loop instead of recursion, which can be faster and avoids stack overflow for large n.
Using Ruby's built-in inject method
ruby
def factorial(n)
  (1..n).inject(1, :*)
end

puts factorial(5)
This is a concise and idiomatic Ruby way using Enumerable's inject method.

Complexity: O(n) time, O(n) space

Time Complexity

The function calls itself n times, so the time grows linearly with n.

Space Complexity

Each recursive call adds a new layer to the call stack, so space used is proportional to n.

Which Approach is Fastest?

The iterative approach is generally faster and uses less memory than recursion because it avoids call stack overhead.

ApproachTimeSpaceBest For
RecursiveO(n)O(n)Clear logic, small inputs
IterativeO(n)O(1)Performance and large inputs
Inject methodO(n)O(1)Concise Ruby code
💡
Always include a base case in recursion to stop infinite calls.
⚠️
Forgetting the base case causes the program to crash with a stack overflow error.