File tree Expand file tree Collapse file tree 1 file changed +5
-5
lines changed
Expand file tree Collapse file tree 1 file changed +5
-5
lines changed Original file line number Diff line number Diff line change 11"""
22 Recursivly compute the Fibonacci sequence using two different methods
3- main() compares the amount of time taken by each algorithm
43 rec_fib(n) requires O(Fibo(n)) operations, whereas binary_rec_fib(n) requires less than O(n)
54"""
65
7- import time
8-
96def rec_fib (n ):
107 if n == 1 :
118 return 1
@@ -20,13 +17,16 @@ def binary_rec_fib(n):
2017 elif n == 0 :
2118 return 0
2219 else :
20+ # This recursive step takes advantage of the following two properties of the fibonacci numbers:
21+ # Fibo(2n) = Fibo(n+1)^2 + Fibo(n)^2
22+ # Fibo(2n+1) = Fibo(n+1)^2 - Fibo(n-1)^2
2323 sgn = n % 2
24- return binary_rec_fib ((n - sgn )/ 2 + 1 )** 2 - ((- 1 )** sgn )* binary_rec_fib ((n + sgn )/ 2 - 1 )** 2
24+ return binary_rec_fib ((n - sgn )/ 2 + 1 )** 2 - ((- 1 )** sgn ) * binary_rec_fib ((n + sgn )/ 2 - 1 )** 2
2525
2626def main ():
2727 times = []
2828 n : int = int (input ("n := " ))
29- for i in range (0 ,n ):
29+ for i in range (0 , n ):
3030 print (binary_rec_fib (i ))
3131
3232if __name__ == "__main__" :
You can’t perform that action at this time.
0 commit comments