Skip to content

Commit c1c2b3f

Browse files
Create factorial_iterative.py
1 parent e2a78d4 commit c1c2b3f

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

maths/factorial_iterative.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
def factorial_iterative(n: int) -> int:
2+
"""
3+
Return the factorial of n using an iterative approach.
4+
Raises ValueError for negative inputs.
5+
"""
6+
if n < 0:
7+
raise ValueError("Input must be a non-negative integer")
8+
result = 1
9+
for i in range(1, n + 1):
10+
result *= i
11+
return result
12+
13+
14+
if __name__ == "__main__":
15+
# simple demonstration
16+
print(factorial_iterative(5)) # expected 120

0 commit comments

Comments
 (0)