diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 9ca90940..838da1ac 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -108,3 +108,4 @@ # Recursion 1. [Tower of Hanoi](Recursion/towerofHanoi.cpp) +2. [Factorial](Recursion/factorial.cpp) diff --git a/algorithms/CPlusPlus/Recursion/factorial.cpp b/algorithms/CPlusPlus/Recursion/factorial.cpp new file mode 100644 index 00000000..d8bf4911 --- /dev/null +++ b/algorithms/CPlusPlus/Recursion/factorial.cpp @@ -0,0 +1,32 @@ +/******************* + * August 09, 2021 + * Leo Nugraha + * Factorial problems via recursive or non-recursive methods + * Run: g++ -std=c++11 factorial.cpp -o factorial + ******************/ +#include + +int FactorialNonRecursion(int number) { + int result = 1; + for (int i=1; i>> FactorialNonRecursion(3) + 6 + >>> FactorialNonRecursion(5) + 120 + >>> FactorialNonRecursion(0) + 1 + >>> FactorialNonRecursion(1) + 1 + """ + if isinstance(number, float): + raise ValueError("Non integer number is not allowed") + if number < 0: + raise ValueError("Negative number is not allowed") # Raise an error here + if number == 0 or number == 1: + return 1 + + result = 1 + for i in range(1, number+1): + result = result * i + return result + +def FactorialRecursion(number): + """ + >>> FactorialRecursion(3) + 6 + >>> FactorialRecursion(5) + 120 + >>> FactorialRecursion(0) + 1 + >>> FactorialRecursion(1) + 1 + """ + if isinstance(number, float) is True: + raise ValueError("Non integer number is not allowed") + if number < 0: + raise ValueError("Negative number is not allowed") + if number == 0 or number == 1: + return 1 + + return number * FactorialRecursion(number-1) + +def main(): + testFactorial = FactorialNonRecursion(5) + print(testFactorial) + + testRecursion = FactorialRecursion(4) + print(testRecursion) + +if __name__ == "__main__": + main()