next up previous
Next: Example: Towers of Hanoi Up: Unit 10 Previous: Example: symmetric sequence of

Multiple recursion

We are in the presence of multiple recursion when the activation of a method can cause more than one recursive activations of the same method.

Example: Recursive method for computing the n-th Fibonacci number.

Fibonacci was a mathematician from Pisa that lived around 1200, who was interested to population growth. He developed a mathematical model to estimate the number of individuals at each generation:

F(n) ... number of individuals at the n-th generation

F(n) = $\displaystyle \cases{
0, & if \(n=0\)\cr
1, & if \(n=1\)\cr
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, ...

We implement a recursive method that takes a positive integer n as parameter and returns the n-th Fibonacci number.

public static long fibonacci(long n) {
  if (n < 0) return -1;  // F(n) is not defined when n is negative
  if (n == 0)
    return 0;
  else if (n == 1)
    return 1;
  else
    return fibonacci(n-1) + fibonacci(n-2);
}


next up previous
Next: Example: Towers of Hanoi Up: Unit 10 Previous: Example: symmetric sequence of