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=1if (number==0)puts "Error! Could not find the factorial of one"elsecounter =1while(counter <= number)factorial = factorial * countercounter += 1endendputs "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.
Example
# create a function to get the factorial of a numberdef getFactorial(number)factorial=1if (number==0)puts "Error! Could not find the factorial of one"elsecounter =1while(counter <= number)factorial = factorial * countercounter += 1endendputs "factorial of #{number} is #{factorial}"end# create some numbers to get their factorialsno1 = 4no2 = 2no3 = 7no4 = 1no5 = 5# get the factorials of the numbers createdgetFactorial(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.