题目:
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; }
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