1 min read

Exercise 8: recursive functions in R

The recursive R function FUN is defined as:

FUN <- function(x) {
  if (x == 0 | x == 1) {
    return(x)
  } else {
    return(FUN(x - 1) + FUN(x - 2))
  }
}

What is the value of x that leads to the following output:

FUN(x)
## [1] 6765
Answer: click to reveal

To help answer this question we first notice that the recursive function FUN defines the Fibonacci sequence. So we are searching for an integer x >= 0 that corresponds to the Fibonacci number 6765. To solve the puzzle we can either look up the first few terms of the Fibonacci sequence or use our function definition to run through some inputs.

To avoid calling FUN manually for different values we can define a vectorized version of the function and run it on the integer inputs between 0 and 20:

  vector_FUN <- Vectorize(FUN)
  vector_FUN(0:20)
  ##  [1]    0    1    1    2    3    5    8   13   21   34
  ## [11]   55   89  144  233  377  610  987 1597 2584 4181
  ## [21] 6765

The answer we get is x = 20:

  x <- 20
  FUN(x)
  ## [1] 6765

For a full collection of R programming tutorials and exercises visit my website at codeRtime.org and the codeRtime YouTube channel.