How to estimate the time of completion of following algorithm for Nth Fibonacci element?
private static double fib(double nth){
if (nth <= 2) return 1;
else return fib(nth - 1) + fib(nth - 2);
}
How to estimate the time of completion of following algorithm for Nth Fibonacci element?
private static double fib(double nth){
if (nth <= 2) return 1;
else return fib(nth - 1) + fib(nth - 2);
}
The exact time complexity of this algorithm is... O(F(n))
where F(N) is nth Fibonacci number. Why? See the explanation below.
Let's prove it by induction. Clearly it holds for the base case (everything is a constant). Why does it hold for F(N)? Let's denote algorithm complexity function as T(N). Then T(N) = T(N-2) + T(N-1)
, because you make 2 recursive calls - one with the argument decreased by 1, one decreased by 2. And this time complexity is exactly Fibonacci sequence.
So F(N)
is the best estimation you can make but you can also say this is O(2^n)
or more precisely O(phi^n)
where phi = (1 + sqrt(5)) / 2 ~= 1.61
. Why? Because nth Fibonacci number is almost equivalent to phi ^ n
.
This bound makes your algorithm non-polynomial and very slow for numbers bigger than something around 30
. You should consider other good algorithms - there are many logarithmic algorithms known for this problem.