in reply to Reaped: Fibonnaci

I was thinking about my post and I realized that some people might not see the usefulness of it. So I'll extend here. The Fibonnaci sequence (invented by a mathematician named Fibonnaci and fascinating because it appears everywhere in nature and is closely connected to the golden ratio) is usually defined in a recursive manner.
sub Fib($) { my $index = shift; return 0 if 0 == $index; return 1 if 1 == $index; return Fib( $index - 1 ) + Fib( $index - 2 ); }
Which is very (very) very slow. Try finding Fib(30). My method uses an iterative approach, here I apply it to the subroutine style as before:
sub Fib($) { my $index = shift; my $acc = 0; my $tmp = 1; while( $index-- ) { # Swap the accumulator and the temp. # Use an Xor swap for fun and to amaze your friends. $acc^=$tmp^=$acc^=$tmp; # Add the two together and store it in the acc. $acc += $tmp; } return $acc; }
Which is significantly faster. You could even implement it with a cache and then do all your work directly on the cache. This has the added bonus of not having to re-calculate the whole sequence every time you call Fib in a program.
{ my @cache = (0, 1); # Localized so only &Fib sees it. sub Fib($) { my $index = shift; return $cache[$index] if defined $cache[$index]; $index -= $#cache; push @cache, $cache[-1] + $cache[-2] while $index--; return $cache[-1]; } }
All of the above code has been tested. But I offer no garauntees.