TheAlgorithms-Ruby/maths/factorial.rb

30 lines
478 B
Ruby
Raw Normal View History

2021-09-03 22:24:58 +02:00
# A ruby program calculate factorial of a given number.
# Mathematical Explanation: The factorial of a number is the product of all the integers from 1 to that number.
# i.e: n! = n*(n-1)*(n-2)......*2*1
2021-04-02 19:31:29 +02:00
2021-04-02 20:22:53 +02:00
#
# Approach: Interative
#
2021-04-02 19:31:29 +02:00
def factorial(n)
2021-04-02 20:22:53 +02:00
return nil if n < 0
2021-09-03 22:24:58 +02:00
2021-04-02 20:22:53 +02:00
fac = 1
while n > 0
fac *= n
n -= 1
end
2021-09-03 22:24:58 +02:00
2021-04-02 20:22:53 +02:00
fac
2021-04-02 19:31:29 +02:00
end
puts '4! = ' + factorial(4).to_s
# 4! = 24
puts '0! = ' + factorial(0).to_s
# 0! = 1
puts '10! = ' + factorial(10).to_s
# 10! = 3628800