Fix bugs and clean up python factorial code
This commit is contained in:
parent
b786aa21a3
commit
4b59767dc6
1 changed files with 7 additions and 3 deletions
|
@ -1,20 +1,24 @@
|
|||
def factorial(n: int) -> int:
|
||||
if n < 2:
|
||||
return n
|
||||
return 1
|
||||
else:
|
||||
return n * factorial(n-1)
|
||||
|
||||
def factorial_iter(n: int) -> int:
|
||||
fact = 1
|
||||
# Grab absolute value to ensure n is a positive integer
|
||||
n = abs(n)
|
||||
for i in range(2, n+1):
|
||||
fact *= i
|
||||
return fact
|
||||
|
||||
user_input = int(input("Insert number to calculate factorial for: "))
|
||||
|
||||
# Get absolute value to force integer into positive range
|
||||
user_input = abs(user_input)
|
||||
|
||||
# Avoid recursion limit
|
||||
if user_input < 1000:
|
||||
print(f"Recursive factorial {user_input}: {factorial(user_input)}")
|
||||
else:
|
||||
print(f"Recursive factorial {user_input}: [Recursion limit error]")
|
||||
|
||||
print(f"Iterative factorial {user_input}: {factorial_iter(user_input)}")
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue