Why is my recursive function so slow in R?

前端 未结 7 2038
栀梦
栀梦 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:08

    A recursive implementation with linear cost:

    fib3 <- function(n){
      fib <- function(n, fibm1, fibm2){
        if(n==1){return(fibm2)}
        if(n==2){return(fibm1)}
        if(n >2){
          fib(n-1, fibm1+fibm2, fibm1)  
        }
      }
    fib(n, 1, 0)  
    }
    

    Comparing with the recursive solution with exponential cost:

    > system.time(fibonacci(35))
      usuário   sistema decorrido 
       14.629     0.017    14.644 
    > system.time(fib3(35))
      usuário   sistema decorrido 
        0.001     0.000     0.000
    

    This solution can be vectorized with ifelse:

    fib4 <- function(n){
        fib <- function(n, fibm1, fibm2){
            ifelse(n<=1, fibm2,
              ifelse(n==2, fibm1,
                Recall(n-1, fibm1+fibm2, fibm1)  
              ))
        }
        fib(n, 1, 0)  
    }
    
    fib4(1:30)
    ##  [1]      0      1      1      2      3      5      8
    ##  [8]     13     21     34     55     89    144    233
    ## [15]    377    610    987   1597   2584   4181   6765
    ## [22]  10946  17711  28657  46368  75025 121393 196418
    ## [29] 317811 514229
    

    The only changes required are changing == to <= for the n==1 case, and changing each if block to the equivalent ifelse.

提交回复
热议问题