Ruby Program to Find Factorial of a Number
You can find the factorial of a number in Ruby using a loop with
def factorial(n); result = 1; (1..n).each { |i| result *= i }; result; end or recursion with def factorial(n); n <= 1 ? 1 : n * factorial(n - 1); end.Examples
Input0
Output1
Input5
Output120
Input10
Output3628800
How to Think About It
To find the factorial of a number, think of multiplying all whole numbers from 1 up to that number. For example, factorial of 5 means 1 × 2 × 3 × 4 × 5. You can do this by starting with 1 and multiplying by each number until you reach the input number.
Algorithm
1
Get the input number n.2
Start with a result variable set to 1.3
Multiply the result by each number from 1 to n.4
After the loop ends, return the result.Code
ruby
def factorial(n) result = 1 (1..n).each do |i| result *= i end result end puts factorial(5)
Output
120
Dry Run
Let's trace factorial(5) through the code
1
Initialize result
result = 1
2
Multiply by 1
result = 1 * 1 = 1
3
Multiply by 2
result = 1 * 2 = 2
4
Multiply by 3
result = 2 * 3 = 6
5
Multiply by 4
result = 6 * 4 = 24
6
Multiply by 5
result = 24 * 5 = 120
7
Return result
return 120
| Iteration | Value of result |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 6 |
| 4 | 24 |
| 5 | 120 |
Why This Works
Step 1: Start with 1
We use result = 1 because multiplying by 1 does not change the value and it is the neutral element for multiplication.
Step 2: Multiply in loop
We multiply result by each number from 1 to n using a loop to accumulate the product.
Step 3: Return final product
After the loop finishes, result holds the factorial value, which we return.
Alternative Approaches
Recursive method
ruby
def factorial(n) return 1 if n <= 1 n * factorial(n - 1) end puts factorial(5)
This uses function calling itself, which is elegant but can cause stack overflow for very large numbers.
Using Ruby's inject method
ruby
def factorial(n) (1..n).inject(1) { |product, i| product * i } end puts factorial(5)
This is a concise way using Ruby's built-in method to multiply all numbers in the range.
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs from 1 to n, so the time grows linearly with n, making it O(n).
Space Complexity
The iterative method uses a fixed amount of memory, so space complexity is O(1).
Which Approach is Fastest?
The iterative loop is generally faster and safer than recursion because it avoids function call overhead and stack limits.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative loop | O(n) | O(1) | Large inputs, performance |
| Recursive method | O(n) | O(n) | Simple code, small inputs |
| Inject method | O(n) | O(1) | Concise Ruby style |
Use recursion for simplicity but loops for better performance with large numbers.
Forgetting that factorial of 0 is 1, which is a special case.