Skip to content

Commit 885b6cf

Browse files
committed
Added factorial.py
1 parent 372cd9d commit 885b6cf

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

factorial.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Factorial:
2+
@staticmethod
3+
def factorial_iteration(number: int, use_while: bool = False) -> int:
4+
factorial: int = 1
5+
if number < 0:
6+
raise ArithmeticError("Factorial of a negative number doesn't exist.")
7+
elif not isinstance(number, int):
8+
raise ArithmeticError("Factorial of non-integers is not supported.")
9+
elif number == 0 or number == 1:
10+
return factorial
11+
else:
12+
if use_while:
13+
i: int = 1
14+
while i < number + 1:
15+
factorial *= i
16+
i += 1
17+
else:
18+
for i in range(1, number + 1):
19+
factorial *= i
20+
return factorial
21+
22+
@staticmethod
23+
def factorial_recursion(number: int) -> int:
24+
if number < 0:
25+
raise ArithmeticError("Factorial of a negative number doesn't exist.")
26+
elif not isinstance(number, int):
27+
raise ArithmeticError("Factorial of non-integers is not supported.")
28+
elif number == 0 or number == 1:
29+
return 1
30+
else:
31+
return number * Factorial.factorial_recursion(number - 1)
32+
33+
34+
if __name__ == '__main__':
35+
input_number = int(input("Enter a positive integer: "))
36+
print("Using iteration (for):", Factorial.factorial_iteration(input_number))
37+
print("Using iteration (while):", Factorial.factorial_iteration(input_number, use_while=True))
38+
print("Using recursion:", Factorial.factorial_recursion(input_number))

0 commit comments

Comments
 (0)