Why is my recursive function so slow in R?

前端 未结 7 1978
栀梦
栀梦 2020-12-02 23:51

The following takes about 30 seconds to run whereas I would expect it to be nearly instant. Is there a problem with my code?

x <- fibonacci(35);

fibonac         


        
7条回答
  •  伪装坚强ぢ
    2020-12-03 00:10

    :-) because you use exponential algorithm!!! So for fibonacci number N it has to call the function 2^N times, which 2^35, which is heck of a number.... :-)

    Use linear algorithm:

    fib = function (x)
    {
            if (x == 0)
                    return (0)
            n1 = 0
            n2 = 1
            for (i in 1:(x-1)) {
                    sum = n1 + n2
                    n1 = n2
                    n2 = sum
            }
            n2
    }
    

    Sorry, edit: the complexity of the exponential recursive algorithm is not O(2^N) but O(fib(N)), as Martinho Fernandes greatly joked :-) Really a good note :-)

提交回复
热议问题