Skip to content

Commit 94fe973

Browse files
Create fibonacci_iterative.py
Add fibonacci_iterative implementation
1 parent e2a78d4 commit 94fe973

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

maths/fibonacci_iterative.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
def fibonacci_iterative(n: int) -> int:
2+
"""
3+
Return the n-th Fibonacci number using an iterative approach.
4+
5+
The function returns the Fibonacci number at index n where:
6+
F(0) == 0, F(1) == 1, F(2) == 1, ...
7+
8+
Examples:
9+
>>> fibonacci_iterative(0)
10+
0
11+
>>> fibonacci_iterative(1)
12+
1
13+
>>> fibonacci_iterative(7)
14+
13
15+
"""
16+
if n < 0:
17+
raise ValueError("Input must be a non-negative integer")
18+
19+
if n == 0:
20+
return 0
21+
a, b = 0, 1
22+
for _ in range(1, n):
23+
a, b = b, a + b
24+
return b
25+
26+
27+
if __name__ == "__main__":
28+
# simple demonstration
29+
print(fibonacci_iterative(7)) # expected 13

0 commit comments

Comments
 (0)