-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
solved recursively and tested. updated iterative solution with new te…
…st. -@iamserda
- Loading branch information
Showing
2 changed files
with
43 additions
and
0 deletions.
There are no files selected for viewing
10 changes: 10 additions & 0 deletions
10
neetcodeio/algostructybeginners/Lv3-Recursion/factorial_iterative.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,18 @@ | ||
def factorial(n): | ||
if n < 0: | ||
return | ||
result = 1 | ||
for i in range(1, n + 1): | ||
result *= i | ||
return result | ||
|
||
|
||
# TESTING ARENA | ||
assert factorial(5) == 5 * 4 * 3 * 2 * 1 | ||
assert factorial(10) == 3628800 | ||
assert factorial(0) == 1 | ||
assert factorial(1) == 1 | ||
assert ( | ||
factorial(100) | ||
== 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 | ||
) |
33 changes: 33 additions & 0 deletions
33
neetcodeio/algostructybeginners/Lv3-Recursion/factorial_recursive.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
def factorial(num): | ||
# base case, stops the recursion. | ||
if num <= 1: | ||
return 1 | ||
else: | ||
# recursive case | ||
return num * factorial(num - 1) | ||
|
||
|
||
# n! = n * (n-1)! | ||
# 1! = 1 | ||
# 0! = 1 | ||
# Space complexity is O(n) because we are stacking | ||
# each recursive call pending until we find a base case | ||
# where num is 1 or num is 0. | ||
|
||
# A never ending recursion leads to memory stack, | ||
# area of memory where function data are stored | ||
# temporarily while the function is running. | ||
# Too many of these recursive-calls will eventually lead to | ||
# a stack overflow, too much data on | ||
|
||
assert factorial(5) == 5 * 4 * 3 * 2 * 1 | ||
assert factorial(10) == 3628800 | ||
assert factorial(0) == 1 | ||
assert factorial(1) == 1 | ||
assert ( | ||
factorial(100) | ||
== 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 | ||
) | ||
|
||
ans = str(factorial(10)) | ||
print(ans, len(ans)) |