欧拉计划 第二题

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.

Fibonacci序列中的每个新术语都是通过添加前两个术语生成的。从1和2开始,前10个术语将是:

1,2,3,5,8,13,21,34,55,89 ......

通过考虑Fibonacci序列中的值不超过四百万的项,找到偶数项的总和。

1.暴力求解法—开辟数组法

从题中我们可以想到一种方法就是开数组,将得到的Fibonacci数放到数组中,一步一步循环相加

(1)用f[0]做计数器,记录有多少个Fibonacci数;

(2)用f[f[0]] = f[f[0] - 1] + f[f[0] - 2]计算Fibonacci数

#include <stdio.h>


int main(){
	int f[500] = {0};
	f[0] = 2;
	f[1] = 1;
	f[2] = 2;
	while (f[f[0]] < 4000000) {
		f[0]++;
		f[f[0]] = f[f[0] - 1] + f[f[0] - 2];
	}
	int sum = 0;
	for(int i = 1; i <= f[0]; i++){
		if(f[i] % 2 == 0) sum += f[i];
	}
	printf("%d\n", sum);
	
	return 0;
}
2.优化开辟数组法

其实我们并不需要开辟那么大的数组记录全部的Fbionacci数,只需要开辟一个大小为3的数组即可,大大减小了空间

#include <stdio.h>


int main(){
	int f[3] = {0};
	f[0] = 1;
	f[1] = 2;
	int sum = 0;
	for(int i = 2; f[2] < 4000000; i++){
		f[i % 3] = f[(i - 1) % 3] + f[(i - 2) % 3];
		if(f[i % 3] % 2 == 0){
			sum += f[i % 3];
		}
	}
	printf("%d\n", sum + 2);
	return 0;

3.最优版plus

由于我们只需要不断更新一个Fibonacci数,就可以进行求和运算,所以我们并不需要开辟数组,只需要不断更新b的值就可以了。

#include <stdio.h>


int main(){
	int a = 1, b = 1, c;
	int sum = 0;
	while(b < 4000000){
		if(b % 2 == 0) sum += b;
		c = b;
		b = b + a;
		a = c;
	}
	printf("%d\n", sum);
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值