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.
Loading...
Related Quiz
- In R, the ______ function can be used to create a scatter plot with a regression line.
- In R, the ______ package provides enhanced functionalities for creating pie charts.
- To handle missing values when finding the max or min value in R, you would use the ______ parameter in the max or min function.
- Suppose you're working with a large dataset in R and need to categorize a numeric column into 'low', 'medium', and 'high' based on specific thresholds. How would you approach this?
- What is the correct way to comment a line in R?