Skip to content

Commit 7187e72

Browse files
committed
feat(day 145): add efficient iterative solution for nth Fibonacci number with large-n support
1 parent a41d93c commit 7187e72

1 file changed

Lines changed: 66 additions & 0 deletions

File tree

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
"""
2+
Nth Fibonacci Number
3+
Given an integer n, return the nth number in the fibonacci sequence.
4+
5+
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. The first 10 numbers in the sequence are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.
6+
"""
7+
8+
import unittest
9+
10+
class NthFibonacciNumberTest(unittest.TestCase):
11+
12+
def test1(self):
13+
self.assertEqual(nth_fibonacci(4), 2)
14+
15+
def test2(self):
16+
self.assertEqual(nth_fibonacci(10), 34)
17+
18+
def test3(self):
19+
self.assertEqual(nth_fibonacci(15), 377)
20+
21+
def test4(self):
22+
self.assertEqual(nth_fibonacci(40), 63245986)
23+
24+
def test5(self):
25+
self.assertEqual(nth_fibonacci(75), 1304969544928657)
26+
27+
28+
def nth_fibonacci(n):
29+
30+
fibo_series = [0, 1]
31+
32+
for i in range(2, n+1):
33+
fibo_series.append(fibo_series[-1] + fibo_series[-2])
34+
35+
return fibo_series[n-1]
36+
37+
def nth_fibonacci(n):
38+
39+
if n < 0:
40+
raise ValueError("n must be non-negative")
41+
42+
if n == 0:
43+
return 0
44+
elif n == 1:
45+
return 1
46+
47+
a, b = 0, 1
48+
49+
for _ in range(2, n+1):
50+
a, b = b , a + b
51+
52+
return a
53+
54+
"""
55+
=> This is an iterative approach (efficient O(n) time, O(1) space)
56+
=> Recursive approach solutions are simpler but inefficient forlarge n (exponential time).
57+
=> For very large n, you'd use matrix exponentiation or fast doubling methods(O(log n)).
58+
"""
59+
60+
61+
62+
if __name__ == "__main__":
63+
print(nth_fibonacci(10))
64+
65+
# print(nth_fibonacci_test(10))
66+
unittest.main()

0 commit comments

Comments
 (0)