偶数斐波那契数列
作者:Mark A. Hershberger
https://projecteuler.net/problem=2
斐波那契数列中的每一项都是前两项的和。从 1 和 2 开始,前 10 项是
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
考虑斐波那契数列中值不超过四百万的项,求所有偶数项的和。
源代码: prob002-hexmode.pl
use v6;
# code exposes a bug in r34733 rakudo, but works in pugs
class Fibonacci {
has @!list = (0, 1);
method next() {
@!list[2] = [+] @!list;
shift @!list;
return @!list[1];
}
}
my $fibber = Fibonacci.new;
my $f;
my @r = gather {
$f = $fibber.next;
while $f < 4000000 {
take (0+$f) if $f % 2 == 0;
$f = $fibber.next;
}
}
say [+] @r;
Perl 6 示例