0

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);
    }
5
  • 2
    You mean complexity? Or actual time? The algorithm runs in O(phi^n) time. Commented Sep 21, 2013 at 14:44
  • I need actual time(how long would it take to calculate Nth element). How to calculate this O(phi^n) for example for 200th Fibonacci number? Commented Sep 21, 2013 at 14:50
  • 2
    Run it for elements 1..10 then you extrapolate using the fact that it's O(phi^2). This won't be very accurate. Is this an exercise? Commented Sep 21, 2013 at 14:56
  • Yes. I have got 45th in 6452 ms; and 10th in 1ms. How to calculate time for 200th? Commented Sep 21, 2013 at 14:57
  • 1
    Why not use the closed form? Commented Sep 21, 2013 at 14:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

How can I find out the time needed to find lets say 300th fib element using my algorithm, given that 10th element is calculated in 1ms?
Given the formula above you need about 2 * 10^62 operations. Assuming that your computer can make 10^9 operations per second on one core you will need 10^45 years. The earth and sun will die until that.
@RCola you need to use System.nanoTime() to calculate the running time. System.currentTimeMillis() isn't accurate enough.
@BoristheSpider, I hope you are joking? He needs to wait 10^45 years.
No, it's better saying c * (1.61 ^10) = 9193461. You have to find c * (1.61^30). Which is easy to find because c * (1.61^10) = c * (1.61^10)^3 = c * (9193461) ^ 3
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.