Complete the code to define a recursive function that calculates the factorial of a number.
factorial <- function(n) {
if (n == 0) {
return(1)
} else {
return(n * factorial([1]))
}
}The recursive call must reduce the number by 1 each time to reach the base case.
Complete the code to define a recursive function that computes the nth Fibonacci number.
fibonacci <- function(n) {
if (n <= 1) {
return(n)
} else {
return(fibonacci([1]) + fibonacci(n - 2))
}
}The Fibonacci sequence is defined as fib(n) = fib(n-1) + fib(n-2).
Fix the error in the recursive function that sums numbers from 1 to n.
sum_to_n <- function(n) {
if (n == 1) {
return(1)
} else {
return(n + sum_to_n([1]))
}
}The recursive call must reduce n by 1 to reach the base case.
Fill both blanks to create a recursive function that counts down from n to 1 and prints each number.
countdown <- function(n) {
if (n == 0) {
return()
}
print([1])
countdown([2])
}The function prints the current number n, then calls itself with n - 1.
Fill all three blanks to define a recursive function that reverses a string.
reverse_string <- function(s) {
if (nchar(s) == 0) {
return("")
} else {
return(paste0(substring(s, [1]), reverse_string(substring(s, [2], [3]))) )
}
}The function takes the last character (substring from nchar(s) to nchar(s)) and appends the reverse of the rest (substring from 1 to nchar(s)-1).
Here, the blanks represent the last character and the rest of the string.