Skip to content

Commit 9b9884d

Browse files
Update fibonacci_iterative.py
1 parent 94fe973 commit 9b9884d

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

maths/fibonacci_iterative.py

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
1-
def fibonacci_iterative(n: int) -> int:
1+
def fibonacci_iterative(term_index: int) -> int:
22
"""
3-
Return the n-th Fibonacci number using an iterative approach.
3+
Return the Fibonacci number at a given index using an iterative approach.
44
5-
The function returns the Fibonacci number at index n where:
6-
F(0) == 0, F(1) == 1, F(2) == 1, ...
5+
Parameters:
6+
term_index (int): Index in the Fibonacci sequence. Must be a non-negative integer.
7+
8+
Returns:
9+
int: The Fibonacci number at the specified index.
710
811
Examples:
912
>>> fibonacci_iterative(0)
@@ -13,17 +16,18 @@ def fibonacci_iterative(n: int) -> int:
1316
>>> fibonacci_iterative(7)
1417
13
1518
"""
16-
if n < 0:
17-
raise ValueError("Input must be a non-negative integer")
19+
if term_index < 0:
20+
raise ValueError("term_index must be a non-negative integer.")
21+
22+
if term_index <= 1:
23+
return term_index
1824

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+
prev, curr = 0, 1
26+
for _ in range(2, term_index + 1):
27+
prev, curr = curr, prev + curr
28+
return curr
2529

2630

2731
if __name__ == "__main__":
28-
# simple demonstration
2932
print(fibonacci_iterative(7)) # expected 13
33+

0 commit comments

Comments
 (0)