Fibonacci sequence by python
Besides there is an interesting post about Fibonaccisequence:
https://www.mathsisfun.com/numbers/fibonacci-sequence.html
This artical is aimed to find out best code to compute Fibonacci by python:
(1)Complexity of algorithm is O(2n)
def fibonacci_1(n): if n==0: return 0 elif n==1: return 1 else: return fibonacci_1(n-1)+fibonacci_1(n-2)
(2)Complexity of algorithm is O(n)
def fibonacci_2(n): result=[0,1] for i in xrange(2,n+1): result.append(result[i-1]+result[i-2]) return result(n)
(3)Complexity of algorithm is logn
def fibonacci_3(n): return recuCal(n)[1] matrix=[0,1,1,1] def recuCal(n): if n == 1: return matrix elif n == 2: return matrixCal(matrix,matrix) elif n % 2: return matrixCal(matrixCal(recuCal(n/2),recuCal(n/2)),matrix) else: return matrixCal(recuCal(n/2),recuCal(n/2)) def matrixCal(matrix1,matrix2): matrix3 = [0,0,0,0] matrix3[0]=matrix1[0]*matrix2[0]+matrix1[1]*matrix2[2] matrix3[1]=matrix1[0]*matrix2[1]+matrix1[1]*matrix2[3] matrix3[2]=matrix1[2]*matrix2[0]+matrix1[3]*matrix2[2] matrix3[3]=matrix1[2]*matrix2[1]+matrix1[3]*matrix2[3] return matrix3