Skip to content

Commit 2b4bca5

Browse files
authored
Add iterative factorial function in factorial_iterative.py
Implement iterative factorial function with error handling.
1 parent 3c88735 commit 2b4bca5

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

maths/factorial_iterative.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
"""
2+
Factorial using Iteration
3+
Time Complexity: O(n)
4+
Space Complexity: O(1)
5+
"""
6+
7+
def factorial(n: int) -> int:
8+
if n < 0:
9+
raise ValueError("Factorial not defined for negative numbers")
10+
11+
result = 1
12+
for i in range(1, n + 1):
13+
result *= i
14+
return result
15+
16+
17+
if __name__ == "__main__":
18+
print(factorial(5))

0 commit comments

Comments
 (0)