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); }
In reply to Re: fibonacci numbers using subroutine?
by Marshall
in thread fibonacci numbers using subroutine?
by derpp
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |