Problem 2:
Each new term int the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the fist 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.
问题2:
每个斐波那契都是由前2个数字相加得到的。第1,2到第10个数为1,2,3,5,8,13,21,34,55,89,…找出不超过400万且是偶数的斐波那契数之和。
分析:
思路1:逐项判断并累加。
思路2:找出相邻偶数之间的关系,如下:
序号:1 2 3 4 5 6 7 8 9 10 11
值: 2 8 34 144
由:a8 = a6 + a7
= a4 + a5 + a5 + a6
= a2 + a3 + 2a5 + a5 +a4
= a2 + 4a5
可得:
a(n+6) = a(n) + 4a(n+3)
验证:当n = 5
a11 = a5 + 4*a8 = 8 + 4*34 = 144
所以:
a(n+6) = a(n) + 4a(n+3)
解:
#include <stdio.h> #define MAX_NUM 4000000 typedef int INT; typedef void VOID; typedef char CHAR; //依次返回斐波那契数 INT Fibo() { static INT n1 = 0; static INT n2 = 1; INT t; t = n1 + n2; n1 = n2; n2 = t; return t; } //依次返回斐波那契数(只返回偶数) INT FiboEven() { static INT n1 = 2; static INT n2 = 8; INT t; t = n1 + 4 * n2; n1 = n2; n2 = t; return t; } INT main(INT argc, INT *argv[]) { /* INT sum; INT n; sum = 0; while ((n=Fibo()) < MAX_NUM) { if(0 == n%2) sum += n; } printf("%d\n", sum); */ INT sum; INT n; sum = 10; n = 0; while ((n=FiboEven()) < MAX_NUM) sum += n; printf("%d\n", sum); return 0; }