kranthi Anne
kranthi Anne

Reputation: 21

Why does this Fibonnacci recursion fails to return an answer for n > 2?

This recursion code doesn't give an output for n > 2. It works if I include the last if condition as else. Why does this happen?

fib <- function(n){

  if(n == 0){
    0
  }
  if(n ==1 ){
    1
  }
  if(n == 2){
   1
  } 
  if (n > 2) {
    print(n)
    fib(n-1) + fib(n-2)
  }

}

Upvotes: 1

Views: 44

Answers (1)

MrFlick
MrFlick

Reputation: 206263

A function by default returns the result of the last value evaluated inside the function. Here you have a bunch of separate if statements that will all be evaluated (your function doesn't return early at any point. Observe

f <- function(a) {
  -99
  if (a==1) {111}
  if (a==2) {22}
}
f(1)
# -- doesn't return anything --
f(2)
# [1] 22
f(3)
# -- doesn't return anything --

When 'a==1', That middle if statement would evaluate to 111 but that value is then discarded when you run the next if statement just like the -99 value was before it. The last expression that was evaluated in this function is the if (a==2) {22} and that will either return 22 or it will return NULL. It won't return the previous values because it has no idea how those would be related without the else statement.

fib <- function(n){    
  if(n == 0){
    return(0)
  }
  if(n ==1 ){
    return(1)
  }
  if(n == 2){
   return(1)
  } 
  if (n > 2) {
    print(n)
    return(fib(n-1) + fib(n-2))
  }
}

Or you could turn those into if/else staments so only one "thing" will be returned

fib <- function(n){    
  if(n == 0){
    0
  } else if(n ==1 ){
    1
  } else if(n == 2){
   1
  } else if (n > 2) {
    print(n)
    fib(n-1) + fib(n-2)
  }
}

Upvotes: 1

Related Questions