发现所有的偶数值项的序列,其中不超过400万总和 [英] Find the sum of all the even-valued terms in the sequence which do not exceed four million
本文介绍了发现所有的偶数值项的序列,其中不超过400万总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Fibonacci序列中的每个新名词是通过添加previous两个术语产生的。通过用1和2开始,前10项将是:
1,2,3,5,8,13,21,34,55,89,...
我制作的节目,但我的答案犯规的比赛。
#包括LT&;&stdio.h中GT;
诠释的main()
{
长期无符号整型我,总和= 0,X = 1,Y = 2,NUM;
对于(i = 0; I< 4000000;我++)
{
NUM = X + Y;
如果(我%2 == 0)
总和+ = NUM;
X = Y;
Y = NUM;
}
的printf(%鲁\\ n,总和);
的getchar();
返回0;
}
解决方案
三个问题,我可以看到:
- 您应该
X = 1,Y = 1
,否则你跳过第一偶数值斐波那契启动 - 您的循环条件应该是
(X + Y)< = 4000000
- 您应该测试
NUM
甚至岬,不是I
。
;
(这些更改后,它应该是显而易见的,你可以省略 I
完全,因此替换为
循环使用,而
循环)
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, ... I made the program but my answer doesnt match.
#include<stdio.h>
int main()
{
long unsigned int i,sum=0,x=1,y=2,num;
for(i=0;i<4000000;i++)
{
num=x+y;
if(i%2==0)
sum+=num;
x=y;
y=num;
}
printf("%lu\n",sum);
getchar();
return 0;
}
解决方案
Three problems I can see:
- You should start with
x = 1, y = 1
, since otherwise you skip the first even-valued Fibonacci; - Your loop condition should be
(x + y) <= 4000000
- You should test
num
for even-ness, noti
.
(After these changes, it should be obvious that you can omit i
entirely, and therefore replace the for
loop with a while
loop)
这篇关于发现所有的偶数值项的序列,其中不超过400万总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文