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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.