We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent e718fb4 commit dd903f9Copy full SHA for dd903f9
1 file changed
Sprint-2/improve_with_caches/fibonacci/fibonacci.py
@@ -1,4 +1,17 @@
1
def fibonacci(n):
2
+ if n < 0:
3
+ raise ValueError("Fibonacci is not defined for negative integers.")
4
if n <= 1:
5
return n
- return fibonacci(n - 1) + fibonacci(n - 2)
6
+
7
+ # Track the last two numbers in the sequence
8
+ prev2 = 0 # fibonacci(0)
9
+ prev1 = 1 # fibonacci(1)
10
11
+ # Calculate upward to n
12
+ for _ in range(2, n + 1):
13
+ current = prev1 + prev2
14
+ prev2 = prev1
15
+ prev1 = current
16
17
+ return prev1
0 commit comments