欧拉计划第2题

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个数字相加得到的。第12到第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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值