(Textbook: ——)
A recursive function is a function that contains a call to itself in its own body.
\(n\) people are in a room. Each person shakes the hand of each other person. How many handshakes are there?
The Fibonacci numbers are defined as follows:
Can we write a function to compute the \(n\)-th Fibonacci number, for any \(n \geq 1\)?
Recall conversion to any desired base:
to_base <- function(b, n) {
if (b > 36) stop("choose a lower base")
digits <- c(0:9, letters)[1:b]
numeral <- ""
curr <- n
while (curr >= b) {
quot <- curr %/% b
rem <- curr %% b
numeral <- str_c(digits[rem + 1], numeral, sep = "")
curr <- quot
}
str_c(digits[curr + 1], numeral, sep = "")
}
to_base(7, 5463)
[1] "21633"
to_base_rec <- function(b, n) {
if (b > 36) stop("choose a lower base")
digits <- c(0:9, letters)[1:b]
## base case
if (n < b) return(digits[n + 1])
## recursive case:
quot <- n %/% b
rem <- n %% b
str_c(Recall(b, quot), digits[rem + 1], sep = "")
}
to_base_rec(7, 5463)
[1] "21633"