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

前端 未结 6 1123
悲&欢浪女
悲&欢浪女 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

    Merge sort time complexity is O(n log(n)). Quick sort best case is O(n log(n)), worst case O(n^2).

    The other answers explain why naive recursive Fibonacci is O(2^n).

    In case you read that Fibonacci(n) can be O(log(n)), this is possible if calculated using iteration and repeated squaring either using matrix method or lucas sequence method. Example code for lucas sequence method (note that n is divided by 2 on each loop):

    /* lucas sequence method */
    int fib(int n) {
        int a, b, p, q, qq, aq;
        a = q = 1;
        b = p = 0;
        while(1) {
            if(n & 1) {
                aq = a*q;
                a = b*q + aq + a*p;
                b = b*p + aq;
            }
            n /= 2;
            if(n == 0)
                break;
            qq = q*q;
            q = 2*p*q + qq;
            p = p*p + qq;
        }
        return b;
    }
    

提交回复
热议问题