How to get the factorial of a number in Ruby

Overview

The factorial of a number is the product of all positive values less than or equal to the number.

In other words, it's the product of an inter and all the integers below it. For example, the factorial of 4 is 24 derived through 4*3*2*1 = 24.

Algorithm

We can get the factorial of a number in Ruby using the logic below:

factorial=1
if (number==0)
puts "Error! Could not find the factorial of one"
else
counter =1
while(counter <= number)
factorial = factorial * counter
counter += 1
end
end
puts "factorial of #{number} is #{factorial}"
Get the factorial of a number in Ruby

Parameters

number: This is the number whose factorial we want to get.

Return value

The value returned is the factorial of the specified number, number.

A flowchart for finding the factorial of a number

Example

# create a function to get the factorial of a number
def getFactorial(number)
factorial=1
if (number==0)
puts "Error! Could not find the factorial of one"
else
counter =1
while(counter <= number)
factorial = factorial * counter
counter += 1
end
end
puts "factorial of #{number} is #{factorial}"
end
# create some numbers to get their factorials
no1 = 4
no2 = 2
no3 = 7
no4 = 1
no5 = 5
# get the factorials of the numbers created
getFactorial(no1)
getFactorial(no2)
getFactorial(no3)
getFactorial(no4)
getFactorial(no5)

Explanation

  • Line 2: We create a function that uses the logic we implement in our syntax to get the factorial of a number.
  • Lines 17–21: We create the numbers whose factorial we want to get.
  • Lines 24–28: We get the factorials of the numbers through the function we create. We then print the results to the console.

Free Resources