in reply to Re^2: fibonacci numbers using subroutine?
in thread fibonacci numbers using subroutine?

I agree. Memoize can help a lot. Here's a little script that I use to get the 1000th, 2000th, 3000th number etc.
#!/usr/bin/perl use strict; use warnings; use Math::Big qw/fibonacci/; use Memoize; memoize('fib', INSTALL => 'fastfib'); my $n = '1000'; print fib(), "\n"; sub fib { foreach ($n) { my @fibonacci = fibonacci($n); print "$fibonacci[$n-1]", "\n"; } }

Replies are listed 'Best First'.
Re^4: fibonacci numbers using subroutine?
by Marshall (Canon) on Aug 20, 2010 at 07:49 UTC
    I thought this code looked a bit odd, so I took the trouble to install Math::Big and play with it.

    1. I think you have an "off by one" problem. $fibonacci[$n-1] does not appear to be correct.
    2. The need for the fib subroutine is unclear to me.
    3. This fibonacci subroutine in the Math::Big library appears to be so fast, that the need for Memoize is also unclear to me...this thing barfs out fibonacci(1000) with incredible speed!

    Below is my testing code:

    #!/usr/bin/perl use strict; use warnings; use Math::Big qw/fibonacci/; my $n=6; print scalar(fibonacci($n)), "\n"; print "".fibonacci($n), "\n"; #another way to force scalar context my @fibs = fibonacci($n); print "@fibs\n"; print $fibs[-1],"\n"; #NOT $n-1, [$n] same as [-1] here. foreach (1000,2000,3000) { #print "".fibonacci($_), "\n\n"; #prints HUGE numbers not shown below } __END__ prints: .....testing the fibonacci of 6, which is indeed 8.... 8 8 0 1 1 2 3 5 8 8
    Anyway, I figure that we are getting pretty "far into the outfield" on this one. Yes, there is a library function for generating a fibonacci number. Yes, it is very fast. Yes, it can calculate these numbers to an incredible number of digits. No, it does not use a recursive algorithm. The library function likes to start the sequence at 0 instead of 1, but that is allowed within the definition of the sequence. Of course it is completely possible that I've misunderstood something - wouldn't be the first time...let me know.