in reply to Reaped: Fibonnaci
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; return 0 if 0 == $index; return 1 if 1 == $index; return Fib( $index - 1 ) + Fib( $index - 2 ); }
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.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; }
All of the above code has been tested. But I offer no garauntees.{ 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]; } }
|
|---|