Recursion: Fibonacci

Screen Shot 2014-09-16 at 9.07.52 PM

Classwork:
Use this class, Fibonacci to develop a better implementation of Fib(num) that saves computed values in an array. Compare the execution time of the original and the new version by choosing the value of num large enough to make a visible difference.

public class Fibonacci
{
   public static long Fib(num)
   {
     if (num == 0) return 0;
     if (num == 1) return 1;
     return Fib(num-1) + Fib(num-2);
   }
   
   public static void main(String [] args)
   {
      for (int i = 0; i < 100; i++)
          StdOut.println(i + " " + Fib(i);
   }
}

Homework:
Given the sequence of values of p and q that are computed when Euclid’s algorithm is used to compute the greatest common divisor of 105 and 24. Extend the code given below to develop a program EuclidGCD that takes two integers and computes their greatest common divisor, printing out the two arguments for each call on the recursive method. Use your program to compute the greatest common divisor of 1111111 and 1234567.

public static in gcd(int p, int q)
{
  if (q === 0) return p;
  int r = p % q;
  return gcd(q, r );
}