-3

I am trying to implement Fibonacci Sequence using recursive Memoization in R. I have Basic idea on R and trying to implement using them.

Here's the code which I tried(not working).

    rm(list = ls())   ##Clearing Environment
    ##Fibonacci_using Recursion
    fibvals <<- numeric(3)
    fibvals[1:length(fibvals)] <- NA
    fib_recursive <- function(n){
        if(is.na(fibvals[n])){ 
            if (n == 1) {
                fibvals[n] <- 0
                return(0)
            } 
            if (n == 2){
                fibvals[1] <- 0
                fibvals[n] <- 1
                return(1)
            } 
        fibvals[n] <- (fib_recursive(n - 1) + fib_recursive(n - 2)) 
        }
        return(fibvals)
    }
    fib_recursive(5)

Can you please suggest corrections and improvements. Thanks.

Larry
  • 71
  • 5

1 Answers1

0

The recursive variant, but without memoization would be something like this:

int fibonnaci(int n) {
    if(n == 1 || n == 2)
       return 1;
    return fibonnaci(n-1) + fibonnaci(n-2);
}

Obviously, this code remakes frequently the same calculations. You have to store the values in an array and the code would look something like this

int fibonnaci(int n) {
    if(a[n]==0)
       a[n]=fibonnaci(n-1) + fibonnaci(n-2);
    return a[n];
}

Also, don't forget about a[MAXN] = {1, 1} first two elements of the string.

scummy
  • 324
  • 1
  • 11