Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 29 lines (22 sloc) 0.671 kB
068a867 backfill
ben hengst authored
1 #!/usr/bin/perl
2 use strict;
3 use warnings;
4 use Memoize;
5
6 =pod
7 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:
8
9 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
10
11 Find the sum of all the even-valued terms in the sequence which do not exceed four million.
12 =cut
13
14 # thanks MJD http://perldoc.perl.org/Memoize.html
15 memoize('fib');
16 sub fib {
17 my $n = shift;
18 return $n if $n < 2;
19 fib($n-1) + fib($n-2);
20 }
21
22 my $i = 2; # we really could start anywhere but we know that 1 = 1 and it's not even
23 my $sum = 0;
24 while ((my $f = fib($i++)) < 4000000) {
25 $sum += $f unless $f %2;
26 }
27 print $sum;
28
Something went wrong with that request. Please try again.