The Fibonacci Set

No Comments

The other knight I was thinking about the Fibonacci set and computer science. When I was a freshman we where even assigned to implement the standard recursive algorithm for the set.
The most basic form of this algorithm:

	private static int basicFib(int i) 
{
if( i == 0 ) return 1;
if( i == 1 ) return 1;
int j = basicFib(i - 1);
int k = basicFib(i - 2);
return j + k;
}
Which calculates the 25th Fibonacci number to be 20,365,011,074 and took 213,935 milliseconds. This hardly seems efficient. After a night with too little sleep I remembered in high-school when I had just started to work on recursion my dad told me, "Recursion is good because it shows concepts easily, but it is rarely the easiest solution." With that in mind I wrote a looping Fibonacci calculation:
	private static long loopFib(int j) 
{
if(j == 1 || j == 0) return 1;
long[] c = {1,1,1};
for(int i = 2; i <= j; i++)
{
c[0] = c[1] + c[2];
c[2] = c[1];
c[1] = c[0];
}
return c[0];
}

Which calculates the 25th Fibonacci number to be 20,365,011,074 calculated in 1 ms. Since the max value of a long as defined in my Java virtual machine turns out to be 9,223,372,036,854,775,807 I think I can calculate a much larger number and still be faster than the recursive method. 9,079,565,065,540,428,013 is the 1000th entry as far as I can calculate with this method, but the precision of my timing isn't precise enough to show any difference between this and the 25th in the sequence.