斐波那契數列偶數項求和(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, ...

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

C代碼:

#include <stdio.h>
#define MAX_LOOP        100
#define MAX_FIB_NUM     4000000
static int fib[MAX_LOOP] = { 0, 1, 2 };
int main()
{
    int value = 2;
    int result = 2;
    int i;

    for( i = 3; i < MAX_LOOP; i++ )
    {
        value = fib[i-1] + fib[i-2];

        if( value >= MAX_FIB_NUM )  break;

        if( (value % 2 == 0) )
        {
            result += value;
        }

        fib[i] = value;
    }

    printf("%d\n",result);

    return 0;
}


python代碼:

fib = {
0 : 0,
1 : 1,
2 : 2,
}

i = len(fib)
ret = 2
while True:
    v = fib[i-1]+ fib[i-2]
    if v >= 4000000 : break
    if v % 2 == 0:
        ret += v
    fib[i] = v
    i += 1

print ret

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章