Skip to content

Commit 870eebf

Browse files
yuriimchgcclauss
authored andcommitted
rewrite the algorithm from scratch (TheAlgorithms#1351)
1 parent 14c23bc commit 870eebf

File tree

1 file changed

+20
-18
lines changed

1 file changed

+20
-18
lines changed

maths/factorial_python.py

+20-18
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,21 @@
1-
"""Python program to find the factorial of a number provided by the user."""
1+
def factorial(input_number: int) -> int:
2+
"""
3+
Non-recursive algorithm of finding factorial of the
4+
input number.
5+
>>> factorial(1)
6+
1
7+
>>> factorial(6)
8+
720
9+
>>> factorial(0)
10+
1
11+
"""
212

3-
# change the value for a different result
4-
NUM = 10
5-
6-
# uncomment to take input from the user
7-
# num = int(input("Enter a number: "))
8-
9-
FACTORIAL = 1
10-
11-
# check if the number is negative, positive or zero
12-
if NUM < 0:
13-
print("Sorry, factorial does not exist for negative numbers")
14-
elif NUM == 0:
15-
print("The factorial of 0 is 1")
16-
else:
17-
for i in range(1, NUM + 1):
18-
FACTORIAL = FACTORIAL * i
19-
print("The factorial of", NUM, "is", FACTORIAL)
13+
if input_number < 0:
14+
raise ValueError('Input input_number should be non-negative')
15+
elif input_number == 0:
16+
return 1
17+
else:
18+
result = 1
19+
for i in range(input_number):
20+
result = result * (i + 1)
21+
return result

0 commit comments

Comments
 (0)