From 9434ab9dc92eb3f79726ffa44b89fde1e7cbe47e Mon Sep 17 00:00:00 2001 From: Sahil Afrid Farookhi Date: Wed, 28 Apr 2021 14:56:40 +0530 Subject: [PATCH] factorial non-recursive non-iterative feature implementation --- DIRECTORY.md | 1 + .../factorial_non_recursive_non_iterative.rb | 44 +++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 maths/factorial_non_recursive_non_iterative.rb diff --git a/DIRECTORY.md b/DIRECTORY.md index a110ecb..fa2aaf9 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -53,6 +53,7 @@ * [Ceil](https://github.com/TheAlgorithms/Ruby/blob/master/maths/ceil.rb) * [Ceil Test](https://github.com/TheAlgorithms/Ruby/blob/master/maths/ceil_test.rb) * [Decimal To Binary](https://github.com/TheAlgorithms/Ruby/blob/master/maths/decimal_to_binary.rb) + * [Factorial Non-recursive and Non-iterative](https://github.com/TheAlgorithms/Ruby/blob/master/maths/factorial_non_recursive_non_iterative.rb) * [Fibonacci](https://github.com/TheAlgorithms/Ruby/blob/master/maths/fibonacci.rb) * [Find Max](https://github.com/TheAlgorithms/Ruby/blob/master/maths/find_max.rb) * [Find Min](https://github.com/TheAlgorithms/Ruby/blob/master/maths/find_min.rb) diff --git a/maths/factorial_non_recursive_non_iterative.rb b/maths/factorial_non_recursive_non_iterative.rb new file mode 100644 index 0000000..17a4f77 --- /dev/null +++ b/maths/factorial_non_recursive_non_iterative.rb @@ -0,0 +1,44 @@ +# A ruby program to find factorial of a given integer +# Factorial of a given integer is defined as the product of all the positive integers less than or equal to the given integer +# Mathematical representation: n! = n * (n - 1) * (n - 2) * ... * 1 + +# +# Non-recursive approach +# + +def factorial(number) + if number < 0 + "Please check your input number! The given number is a negative number." + else + if number == 0 + "The factorial of #{number} is 1." + else + "The factorial of #{number} is #{(1..number).inject(:*)}." + end + end + rescue + "Error: Please provide integer only!" +end + +# Valid inputs +puts factorial(0) +# The factorial of 0 is 1. + +puts factorial(4) +# The factorial of 4 is 24. + +puts factorial(10) +# The factorial of 10 is 3628800. + +puts factorial(1) +# The factorial of 1 is 1. + +puts factorial(-5) +# Please check your input number! The given number is a negative number. + +# Invalid inputs +puts factorial("a") +# Error: Please provide integer only! + +puts factorial("2") +# Error: Please provide integer only!