Fibonacci Sequence Problem
1. Problem
Given an integer , calculate the term of the Fibonacci sequence .
is defined by:
2. Naive Solution
def fibonacci(n:int):
if n==0:
return 0
elif n==1:
return 1
return fibonacci(n-1)+fibonacci(n-2)
Let be the cost of calculating using this algorithm
2.1 Lower Bound
We have:
With , and by recursion we can prove that:
But, is increasing, so:
By that we have
2.2 Upper Bound
We also have for some fixed :
We can prove by induction that:
Also by induction, we can prove that:
So we have:
2.3 Sharper Bounds
In fact, it can be proven that:
So we have:
We can do even more than that, using more advanced techniques, it can be established that:
3. Better Solution
def fibonacci(n:int):
u,v=(0,1)
for i in range(n):
u,v=(v,u+v)
return u
Let be the cost of this algorithm for an input :
4. Fast Solution
def matMul(A:Mat[p,q],B:Mat[q,r]):
C:Mat[2,2]=zeros([2,2])
for i in range(p):
for j in range(q):
for k in range(2):
C[i,j]+=A[i,k]*B[k,j]
return C
def matPow(A:Mat[p,p],n:int):
if n == 0:
return identity([2,2])
elif n == 1:
return A
B=matPow(matMul(B,B),n//2)
return matMul(B,matPow(A,n%2))
def matVectMul(A:Mat[p,q],u:Vect[q]):
v:Vect[q]=zeros(q)
for i in range(p):
for j in range(q):
v[i]+=A[i,j]*u[j]
return v
def fibonacci(n:int):
F:Mat[2,2]=Mat([[0,1],[1,1]])
u:Vect[2]=Vect([0,1])
v=matPow(F,n)*u
return v[0]
a. Complexity of matMul
b. Complexity of matPow
c. Complexity of matVectMul
d. Complexity of fibonacci
We have . So we have the complexity of fibonacci
is