chore: add recursion factorial C++ and Python (#413)

pull/418/head
Leo Nugraha 2021-08-10 20:25:17 +08:00 committed by GitHub
parent 82250706f8
commit 9e0e9ee244
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 89 additions and 0 deletions

View File

@ -108,3 +108,4 @@
# Recursion # Recursion
1. [Tower of Hanoi](Recursion/towerofHanoi.cpp) 1. [Tower of Hanoi](Recursion/towerofHanoi.cpp)
2. [Factorial](Recursion/factorial.cpp)

View File

@ -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 <iostream>
int FactorialNonRecursion(int number) {
int result = 1;
for (int i=1; i<number+1; ++i)
result = result * i;
return result;
}
int FactorialRecursion(int number) {
if (number == 0 || number == 1) {
return 1;
}
return number * FactorialRecursion(number-1);
}
int main(int argc, char *argv[]){
int testNonRecursion = FactorialNonRecursion(5);
std::cout << testNonRecursion << "\n";
int testRecursion = FactorialRecursion(3);
std::cout << testRecursion << "\n";
return 0;
}

View File

@ -16,6 +16,10 @@
1. [Karatsuba](multiplication/karatsuba.py) 1. [Karatsuba](multiplication/karatsuba.py)
## Recursion
1. [Factorial](recursion/factorial.py)
## Scheduling ## Scheduling
1. [Interval Scheduling](scheduling/interval_scheduling.py) 1. [Interval Scheduling](scheduling/interval_scheduling.py)

View File

@ -0,0 +1,52 @@
def FactorialNonRecursion(number):
"""
>>> 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()