The Fibonacci sequence starts with 0 and 1. After that, the \(n\)th fibonacci number, denoted \(f(n)\), is the sum of the prior two (\(f(n-2) + f(n-1)\)). Here’s a table with the first few values in the sequence:
\(n\) | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
---|---|---|---|---|---|---|---|---|---|
f(\(n\)) | 0 | 1 | 1 | 2 | 3 | 5 | 8 | 13 | 21 |
Here’s some pseudocode for a method that calculates the \(n\)th fibonacci number:
fib(n):if n <= 1:
return n;
return fib(n-1) + fib(n-2)
fib(3)
, how many times is fib
called in total (including the call to fib(3)
)?fib(4)
, how many times is fib
called in total?fib
?Find the two bugs in the following pseudocode. Hint: refer back to the four-step procedure for understanding recursive methods.
duplicate(String s):
if s.length() == 0:
return s
return s[0] + s[0] + duplicate(s)
You asked to write a recursive method with the following specification:
/** Sum the digits of n. Precondition: n >= 0. */
Devise a recursive definition of the solution to this problem for all \(n > 0\). Hint: consider using mod and integer division.
Write a line of code to replace the TODO comment in the method below to implement your recursive definition and correctly complete the method.
/** Sum the digits of n. Precondition: n >= 0. */
public static int sumDigits(int n) {
if (n == 0) {
return 0;
}
// TODO recursive case
}