Exercise 8: recursive functions in R

[This article was first published on R programming tutorials and exercises for data science and mathematics, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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
To leave a comment for the author, please follow the link and comment on their blog: R programming tutorials and exercises for data science and mathematics.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)