#!/usr/bin/perl -w
################
#
# more efficient version of fibonnaci
#
################
use strict;

our @fibs = (0,1);

# Calculate a term in the fibonnaci series recursively.
# Usage: $x = fib(4);   # returns the 4th fibonnaci number.
sub fib {
  my ($i) = @_;
  if (defined $fibs[$i]){
    return $fibs[$i];
  }
  else {
    make_fibs_to($i);
    return $fibs[$i];
  }
}

# Fill in the list of fibonnic numbers starting past the last known
# and continuing up to the one we need.
sub make_fibs_to{
  my ($i) = @_;
  for my $j ( scalar(@fibs) .. $i ){
    $fibs[$j] = $fibs[$j-1] + $fibs[$j-2];
  }
}

print " the 50th fibonnaci number is " , fib(50) , "\n";
for my $k (0..10){
  print " fib($k)=", fib($k), "\n";
}
