Fibonacci numbers

(definition taken from webopedia.com)

A series of whole numbers in which each number is the sum of the two preceding numbers. Beginning with 0 and 1, the sequence of Fibonacci numbers would be 0,1,1, 2, 3, 5, 8, 13, 21, 34, etc. using the formula n = n(-1) + n(-2), where the n(-1) means "the last number before n in the series" and n(-2) refers to "the second last one before n in the series.”

In computer programming, Fibonacci numbers give a model for designing recursive programming algorithms where the time for any routine is the time within the routine itself, plus the time for the recursive calls.

The Fibonacci numbers were originally defined by the Italian mathematician Fibonacci, also known as Leonardo da Pisa, in the 13th century to model the growth of rabbit populations.

 

Fibonacci Numbers Recursive Implementation 1

(note: when recursively calling fibonacci(n-2) had to remember the result of calling fibonacci(n-1) )

public class Fibonacci
{
     public static int fibonacci(int n)
        {
            if (n <= 1)
                return n;
            else
                return fibonacci(n-1) + fibonacci(n-2);
        }
    public static void main(String[] args)
        {
            for (int i = 0; i < 20; i++)
                System.out.println("F_" + i + " = " + fibonacci(i));
        }
}

Fibonacci with Tail Recursion (does not have to remember anything while making the recursive call)

  • Tail-recursion:
    • a special case of linear recursion.
    • the value to be returned is computed directly by a recursive call.

 

Algorithm fibonacci(n)
Input: an integer n >= 0
Output: the pair of Finonacci numbers (Fn,Fn-1)

     if n = 0 then
          return 0
     else if n = 1 then
          return (1,0)
     else
          (f2,f1) <- fibonacci(n-1)
          return (fn2 + fn1, fn2)

Iterative Implementation

Algorithm fibonacci(n)
Input: an integer n >= 0
Output: the pair of Finonacci numbers (Fn,Fn-1)

     if n = 0 then
          return 0

     f1 <- 0
     f2 <- 1
     while n > 1 do
          tmp <- f1
          f1 <- f2
          f2 <- f2 + tmp
     
      return f2

© Lynne Grewe