Why is the Fibonacci Sequence Big O(2^n) instead of O(logn)?

前端 未结 6 1078
悲&欢浪女
悲&欢浪女 2021-01-31 06:29

I took discrete math (in which I learned about master theorem, Big Theta/Omega/O) a while ago and I seem to have forgotten the difference between O(logn) and O(2^n) (not in the

6条回答
  •  一向
    一向 (楼主)
    2021-01-31 07:12

    Consider the following implementation

    int fib(int n)
    {
        if(n < 2)
          return n;
        return fib(n-1) + fib(n-2)
    }
    

    Let's denote T(n) the number of operations that fib performs to calculate fib(n). Because fib(n) is calling fib(n-1) and fib(n-2), it means that T(n) is at least T(n-1) + T(n-2). This in turn means that T(n) > fib(n). There is a direct formula of fib(n) which is some constant to the power of n. Therefore T(n) is at least exponential. QED.

提交回复
热议问题