sub Fib($)
{
my $index = shift;
return 0 if 0 == $index;
return 1 if 1 == $index;
return Fib( $index - 1 ) + Fib( $index - 2 );
}
####
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;
}
####
{
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];
}
}