-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfibonacci_series.py
82 lines (71 loc) · 2.09 KB
/
fibonacci_series.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
from time import time
class Solution:
values = {
0: 0,
1: 1,
2: 1
}
def fibo(self, n):
"""Compute nth fibonacci number and return within O(logn) time
Args:
n (int)
Returns:
int: nth Fibonacci number
"""
if n in [0, 1, 2]:
return self.values[n]
m = 3
k = 2
f = self.values
while True:
# print("m: {}".format(m))
# print("m: {}\tk: {}".format(m, k))
# print("(m - k + 1): {}\t(m - k): {}".format(m - k + 1, m - k))
if m not in self.values:
if (m - k + 1) not in self.values:
self.fibo(m - k + 1)
if (m - k) not in self.values:
self.fibo(m - k)
if k not in self.values:
self.fibo(k)
if (k - 1) not in self.values:
self.fibo(k - 1)
f[m] = f[k]*f[m-k+1] + f[k-1]*f[m-k]
if m == n:
break
if (m - 1) not in self.values:
f[m - 1] = self.fibo(m - 1)
k = m
if 2*m - 1 > n:
m = n
else:
m = 2*m - 1
return f[n]
def fibo2(self, n):
"""Compute nth fibonacci number and return within O(n) time
Args:
n (int)
Returns:
int: nth Fibonacci number
"""
if n in [0, 1, 2]:
return self.values[n]
m = 3
f = self.values
while True:
f[m] = f[m - 1] + f[m - 2]
if m >= n:
break
m += 1
return f[n]
if __name__ == "__main__":
while True:
n = int(input("Enter n: "))
t1 = time()
print("\n\tFibo(n): {}".format(Solution().fibo(n)))
t2 = time()
print("\tTotal time for O(logn): {} seconds".format(t2- t1))
t1 = time()
print("\n\tFibo(n): {}".format(Solution().fibo2(n)))
t2 = time()
print("\tTotal time O(n): {} seconds\n".format(t2- t1))