CS341
2
• and F(n − 2) + F(n − 1), if n > 1
F(0), F(1), F(2), . . . is called the sequence of Fibonacci numbers, and it starts with: 0, 1, 1, 2, 3, 5,
8, 13, 21, . . .
Implement a recursive method that takes a positive integer n as parameter and returns the n-th
Fibonacci number.
Exercise 4:
Rewrite the previous program using loops and compare their running time.
Exercise 5:
Provide an implementation of the method that calculates the Ackermann function A(m, n), which
is defined as follows:
A(m, n) =
n + 1, if m = 0 (base case)
A(m − 1, 1), if n = 0 (recursive case)
A(m − 1, A(m, n − 1)), otherwise (recursive case)
Note that the Ackermann function grows very fast (it is a non-elementary function): A(x, x) grows
faster than any tower of exponentials 22 ···2^x .
Exercise 6
A palindrome is a string that is the same forward and backward. It is possible to define a
palindrome recursively as follows:
• A string containing fewer than 2 letters is always a palindrome.
• A string containing 2 or more letters is a palindrome if its first and last letters are the same,
and the rest of the string (without the first and last letters) is also a palindrome.
Write a program that prompts for and reads in a string, then prints a message saying whether it is
a palindrome. Your main method should read the string and call a recursive (static) method
palindrome that takes a string and returns true if the string is a palindrome, false otherwise.