(Textbook: Section 16.1)
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"
fib <- function(n) {
## Base cases:
if (n %in% c(1, 2)) {
return(1)
}
## Recursive case:
Recall(n - 1) + Recall(n - 2)
}
fib(10)
[1] 55
Seems to work just fine.
Try:
Takes a scary long time to finish.
Don’t even bother with:
The number of recalls that fib()
must make grows exponentially with the size of n
.
Let’s investigate this:
## highest fib number to find:
m <- 25
## set up some results vectors:
calls <- numeric(m)
fibs <- numeric(m)
for (i in 1:m) {
counter <- 0
fibs[i] <- fib2(i)
calls[i] <- counter
}
calls - (fibs + fibs - 1)
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Math Fact: the number of calls made by the fib()
function when finding the nth Fibonacci number is:
\[2 \times F_n - 1.\]