Iterating Over the Fibonacci Numbers

September 5, 2001, 11:00 PM —  ITworld — 

Consider the Fibonacci numbers (0,1,1,2,3,5,8,13,21,34,...), where the
next number is the sum of the previous two in the series. We could
create a recursive routine to calculate these:

#!/usr/bin/perl -w
use strict;

sub fib {
my $n = shift;
return $n if $n < 2;
fib($n-1) + fib($n-2);
}

for(0..9) {
print fib($_),"\n";
}
__END__

However, due to its recursive nature, the fib() routine must
recalculate earlier numbers in the series every time it is called. One
simple solution is to create a cache that stores numbers in the series,
and then have the function use those if they exist. This is called
Memoization and there is a Memoize module on CPAN (we discussed this
module back in May 2001). This technique is a trade off between using
more space (the cache) and gaining more speed.

If one only wishes to iterate through the series in order (perhaps with
breaks to do other processing), then another solution is to create an
iterator using a closure:

#!/usr/bin/perl -w
use strict;
sub gen_fib {
my($curr, $next) = (0,1);
return sub {
my $fib = $curr;
($curr, $next) = ($next, $curr + $next);
return $fib;
};
}

my $fib_stream1 = gen_fib();
my $fib_stream2 = gen_fib();

# print first 5 fibonacci numbers from stream 1
print "Stream One:";
for(1..5){
print $fib_stream1->(), ' ';
}
print "\n";

# print first 10 from stream 2
print "Stream Two:";
for (1..10) {
print $fib_stream2->(), ' ';
}
print "\n";

# print next 5 from stream 1
print "Stream One:";
for(1..5){
print $fib_stream1->(), ' ';
}
print "\n";
__END__

This technique offers some advantages. It only stores enough state to
calculate the next number (without recursion) rather than all the
previous numbers in the series as memoization does, and you can have
more than one independent iterator (or stream) in the same program.
However, this technique also has some disadvantages. It is only useful
in cases where you actually want to iterate through the series. It is
not useful for calculating the Nth Fibonacci number (which the
recursive solution could be used for).

You do not have to iterate over mathematical functions, you can iterate
over anything. It is possible to create an iterator that iterates over
N arrays in n-tuples (i.e., get the first item from each array, then
the second, etc...). With an array of array refs as a table, this is
analagous to iterating over the columns rather than the rows.

» posted by ITworld staff

ITworld

Sign up for ITworld's Daily newsletter
Follow ITworld on Twitter @IT_world

I like it!
Post a comment
The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
peer-to-peer

Esther Schindler
If the comments are ugly, the code is ugly

claird
SVG a graphics format for 21st century

pasmith
Take Chrome OS for a test spin

Sandra Henry-Stocker
Solaris Tip: Have Your Files Changed Since Installation?

sjvn
64-bits of protection?

jfruh
Android fragments vs. the iPhone monolith

mikelgan
What Gizmodo missed about the Pro WX Wireless USB disk drive

 

Sidekick: The Good News & the Bad News
Either way you look at it Microsoft Data Center management did not follow standards or best practices in this failure. In which case it makes me wonder more about the outsourcing of corporate data much less personal data.
- mburton325

Join the conversation here

The Daily Tip

The Daily TipQuick, practical advice for IT pros. Made fresh daily.

Hot tips:

Want to cash in on your IT savvy? Send your tip to tips@itworld.com. If we post it, we'll send you a $25 Amazon e-gift card.

Newsletters

Subscribe to ITWORLD TODAY and receive the latest IT news and analysis.

I would like to receive offers via email from ITworld partners.
By clicking submit you agree to the terms and conditions outlined in ITworld's privacy policy.
Featured Sponsor

AISO founders envisioned a Web hosting company that was environmentally friendly. While the company employed energy-efficient innovations like solar panels, its infrastructure produced unacceptable power and cooling requirements. Find out how AISO leveraged AMD technology to overcome their challenge in this case study white paper.

In this whitepaper, Scalar explores the opportunity to change the landscape with respect to mission critical databases built around Oracle. Leveraging technologies such as Linux, high-end commodity processing power and Oracle RAC technology to architect, design, build and maintain database infrastructure that delivers maximum availability, reliability and performance at a fraction of traditional cost.

On a typical day, weather.com, the Web site for The Weather Channel in Atlanta, serves up between 15 million and 20 million page views. But in September 2004, when back-to-back hurricanes ransacked Florida, the peak traffic on one day more than tripled: over 70 million page views by more than 7 million unique visitors. Read the full success story now.

Marketplace