欧拉计划题目2

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, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

http://projecteuler.net/problem=2

 

斐波那契数列中的每一项被定义为前两项之和。从1和2开始,斐波那契数列的前十项为:

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

考虑斐波那契数列中数值不超过4百万的项,找出这些项中值为偶数的项之和。

http://pe.spiritzhang.com/index.php/2011-05-11-09-44-54/3-24

#!perl -w
use 5.010;
use strict;
my $sum;
my @list = (1 ,2);
for (2..100){
    if ($list[$_-2] +$list[$_-1] < 4000000){
        push @list , $list[$_-2] +$list[$_-1];
        
    }
    else {
        last;
    }
}
#say "@list";
map {$sum += $list[$_] }grep {$_ % 3 == 1}(0..$#list);
say $sum;

说明一点:

稍微研究一下这个数列,就可以发现数列各元素奇偶性为 奇偶奇 奇偶奇 奇偶奇 ... 所以才有以下写法:

map {$sum += $list[$_] }grep {$_ % 3 == 1}(0..$#list);
posted @ 2012-10-07 18:37  qinbin  阅读(150)  评论(0编辑  收藏  举报