Skip to content
This repository
tree: 3e5a26927e
Fetching contributors…

Cannot retrieve contributors at this time

file 27 lines (22 sloc) 0.671 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#!/usr/bin/perl
use strict;
use warnings;
use Memoize;

=pod
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

Find the sum of all the even-valued terms in the sequence which do not exceed four million.
=cut

# thanks MJD http://perldoc.perl.org/Memoize.html
memoize('fib');
sub fib {
   my $n = shift;
   return $n if $n < 2;
   fib($n-1) + fib($n-2);
}

my $i = 2; # we really could start anywhere but we know that 1 = 1 and it's not even
my $sum = 0;
while ((my $f = fib($i++)) < 4000000) {
   $sum += $f unless $f %2;
}
print $sum;
Something went wrong with that request. Please try again.