Skip to content

Commit 2f674ef

Browse files
committed
Added a faster recursive fibonacci algorithm
1 parent c685585 commit 2f674ef

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed
Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
"""
2-
Recursivly compute the Fibonacci sequence
2+
Recursivly compute the Fibonacci sequence using two different methods
3+
main() compares the amount of time taken by each algorithm
4+
rec_fib(n) requires O(Fibo(n)) operations, whereas binary_rec_fib(n) requires less than O(n)
35
"""
46

7+
import time
8+
59
def rec_fib(n):
610
if n == 1:
711
return 1
@@ -10,10 +14,19 @@ def rec_fib(n):
1014
else:
1115
return rec_fib(n-1)+rec_fib(n-2)
1216

17+
def binary_rec_fib(n):
18+
if n == 2 or n == 1:
19+
return 1
20+
elif n == 0:
21+
return 0
22+
else:
23+
sgn = n % 2
24+
return binary_rec_fib((n-sgn)/2+1)**2 - ((-1)**sgn)*binary_rec_fib((n+sgn)/2-1)**2
25+
1326
def main():
27+
times = []
1428
n : int = int(input("n := "))
15-
for i in range(0, n):
16-
print(rec_fib(i))
29+
print(binary_rec_fib(i))
1730

1831
if __name__ == "__main__":
1932
main()

0 commit comments

Comments
 (0)