为什么此斐波那契密码不正确? [英] Why is this Fibonacci code not correct?
本文介绍了为什么此斐波那契密码不正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
欧拉计划问题2.
斐波那契数列中的每个新术语都是通过将前两个术语相加而生成的.从1和2开始,前10个术语将是:
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,...
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
通过考虑斐波那契数列中值不超过400万的项,找到偶值项的总和.
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
我的解决方案:
int firstNum = 1;
int secondNum = 2;
int resultNum = firstNum + secondNum;
int sum = 0;
for (int i = 0; i < 4000000; i++)
{
firstNum = i;
secondNum = i;
if(resultNum == firstNum + secondNum)
{
sum += resultNum;
Console.WriteLine(sum);
}
}
为什么这是不正确的,您可以引导我采取正确的思维方式吗?
Why is this not correct and can you guide me into the right way of thinking?
推荐答案
尝试一下:
int n1, n2, fib;
//n1 = 0;
//n2 = 1;
n1 = 1;
n2 = 1;
fib = n1 + n2;
while (fib < 4000000)
{
n2 = n1;
n1 = fib;
fib = n1 + n2;
}
然后找到偶数fib数并将其求和
Then find the even fib numbers and sum it
这篇关于为什么此斐波那契密码不正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文