in reply to fibonacci numbers using subroutine?
Below I have coded both a non-recursive and a recursive algorithm in pretty much "run of the mill" implementations. They both produce the same results although the recursive algorithm is ridiculously slow.
Sorry I didn't crank up the iterations far enough to get a meaningful result for the non-iterative version because if I did that, I'd have to go take a long nap waiting for the recursive version to finish! However, the benchmark below shows just how silly the comparison between the two is. "Un-comment" the print statements and crank down the iterations to verify output is the same.
#!/usr/bin/perl -w use strict; use Benchmark; timethese (10, { Normal=> q{ foreach (20..25) { #print "number $_ : fibonacci ",fibonacci($_),"\n"; my $f = fibonacci($_); } }, Slow => q{ foreach (20..25) { #print "number $_ : fibonacci ",fibonacci_slow($_),"\n"; my $f = fibonacci_slow($_); } }, } ); =prints: Benchmark: timing 10 iterations of Normal, Slow... Normal: 0 wallclock secs ( 0.00 usr + 0.00 sys = 0.00 CPU) (warning: too few iterations for a reliable count) Slow: 7 wallclock secs ( 6.24 usr + 0.00 sys = 6.24 CPU) @ 1 +.60/s (n=10) =cut sub fibonacci { my $number = shift; my $curnum = 1; my $prevnum = 1; my $sum; if ($number ==1 || $number ==2){ return 1;} $number -= 2; while ($number--) { $sum = $curnum + $prevnum; $prevnum = $curnum; $curnum = $sum; } return $sum; } sub fibonacci_slow { my $number = shift; if ($number ==1 || $number ==2){ return 1;} return fibonacci_slow($number-1) + fibonacci_slow($number-2); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: fibonacci numbers using subroutine?
by BrowserUk (Patriarch) on Aug 20, 2010 at 10:31 UTC | |
by Marshall (Canon) on Aug 20, 2010 at 12:45 UTC | |
by BrowserUk (Patriarch) on Aug 20, 2010 at 12:53 UTC | |
by Marshall (Canon) on Aug 20, 2010 at 13:06 UTC | |
by JavaFan (Canon) on Aug 20, 2010 at 13:13 UTC | |
by BrowserUk (Patriarch) on Aug 20, 2010 at 13:23 UTC | |
|
Re^2: fibonacci numbers using subroutine?
by Anonymous Monk on Aug 20, 2010 at 05:32 UTC | |
by Khen1950fx (Canon) on Aug 20, 2010 at 05:53 UTC | |
by Marshall (Canon) on Aug 20, 2010 at 07:49 UTC |