You should have told us that it's Euler Problem #2
I took some liberties, especially using unshift and pop (which is kind of optional) facilitated to fix a conceptional bug of yours¹.
Feel free to ask if you have problems understanding.
HTH! :)
PS: @Harangzsolt33 I had no problems calculating for 4e12 or bigger, the limit is rather integer accuracy and not recursion overhead.
#!/usr/bin/perl use v5.14; use strict; use warnings; my $result = 0; my $level = 2; # next is F2 my $max_val = 4_000_000; my $max_rec = 1000; my $DBG = 1; fib(1,0); # F1,F0 print $result; sub fib { my @frame = @_; #my $DBG = 1; unshift @frame, $frame[0] + $frame[1]; # prepend next level Fib +(see footnote 1) pop @frame; # remove tailing Fib (opt +ional) count($frame[0]); say "Fib(" . $level++ . ") = $frame[0]" if $DBG; say " ... # \@frame = (@frame)" if $DBG; # playing safe with deep recursion die "May recursion $max_rec exceeded" if $level > $max_rec; return fib(@frame) unless($frame[0] >= $max_val); } sub count { my ($increment) = @_; #my $DBG = 1; if(($increment % 2) == 0){ say "adding Fib($level) = $increment to $result" if $DBG; $result += $increment; } }
activating the $DBG flags will show you debug information.
¹) you can also do a list assignment instead of unshift and pop. Your code suffered from timing problems when overwriting.
Cheers Rolf
(addicted to the Perl Programming Language :)
see Wikisyntax for the Monastery
In reply to Re: How am i doing?
by LanX
in thread How am i doing?
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |