Project Euler:Problem 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, ...

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

 

题目要求:求Fibonacci数列f(n)中不大于4000,000且为偶数项数之和。

代码如下:

#include <stdio.h>

int main()
{
    long n = 4000000;
    long f1, f2 = 1, f3 = 0;
    long sum = 0;
    for (f1 = 0; f2 <= n;)
    {
        f3 = f2 + f1;

        if (f3 % 2 == 0)   // 如果是偶数
            sum += f3;

        f1 = f2;
        f2 = f3;
    }
    printf("%d", sum );
}

posted @ 2010-10-17 21:56  jeff_nie  阅读(140)  评论(0编辑  收藏  举报