Imagine you need to create a recursive function in R that computes the nth Fibonacci number. How would you do this?

  • fibonacci <- function(n) { if (n <= 1) { return(n) } else { return(fibonacci(n - 1) + fibonacci(n - 2)) } }
  • fibonacci <- function(n) { if (n <= 1) { return(0) } else { return(fibonacci(n) + fibonacci(n - 1)) } }
  • fibonacci <- function(n) { if (n <= 1) { return(1) } else { return(fibonacci(n + 1) + fibonacci(n - 1)) } }
  • All of the above
To create a recursive function in R that computes the nth Fibonacci number, you can use the following code: fibonacci <- function(n) { if (n <= 1) { return(n) } else { return(fibonacci(n - 1) + fibonacci(n - 2)) } }. The function checks if the input n is less than or equal to 1. If it is, it returns n (base case). Otherwise, it recursively calls itself to calculate the Fibonacci number by summing the two previous Fibonacci numbers.
Add your answer
Loading...

Leave a comment

Your email address will not be published. Required fields are marked *