In this article, we will explore how to calculate factorials for non-negative integers using Ruby. We’ll provide a comprehensive guide with step-by-step explanations and real-world examples to help you understand and implement factorial calculations effectively.
Understanding factorials
Before we dive into Ruby code, let’s clarify what factorials are. The factorial of a non-negative integer n
, denoted as n!
, is the product of all positive integers from 1 to n
. For example, 5!
is equal to 5 × 4 × 3 × 2 × 1
, which equals 120
.
Approach 1: Using iteration
The most straightforward way to calculate factorials is through iterative multiplication. Here’s a Ruby function that computes the factorial of a given non-negative integer n
:
def factorial_iterative(n)
result = 1
if n < 0
return "Factorial is undefined for negative numbers"
elsif n == 0 || n == 1
return 1
else
(2..n).each do |i|
result *= i
end
return result
end
end
# Test the function with an example
n = 5
result = factorial_iterative(n)
puts "Factorial of #{n} is #{result}" # Output: "Factorial of 5 is 120"
In this approach, we initialize a result
variable to 1 and then iterate from 2 to n
, multiplying the result by each integer along the way.
Approach 2: Using recursion
Factorial calculations can also be implemented using recursion. Here’s a Ruby function that calculates factorials recursively:
def factorial_recursive(n)
if n < 0
return "Factorial is undefined for negative numbers"
elsif n == 0 || n == 1
return 1
else
return n * factorial_recursive(n - 1)
end
end
# Test the function with an example
n = 5
result = factorial_recursive(n)
puts "Factorial of #{n} is #{result}" # Output: "Factorial of 5 is 120"
In the recursive approach, we check for base cases (when n
is 0 or 1) and then recursively call the factorial_recursive
function with a reduced value of n
until we reach the base case.