gpt4 book ai didi

c# - 偶数的斐波那契数列和

转载 作者:行者123 更新时间:2023-12-02 22:33:17 39 4
gpt4 key购买 nike

我在 stackoverflow 上遇到了这个问题:

"I'm having some trouble with this problem in Project Euler. Here's what the question asks: 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, ... Find the sum of all the even-valued terms in the sequence which do not exceed four million."

最佳答案是这个(在 VS2010 中不能为我编译...为什么?):

    IEnumerable<int> Fibonacci()
{
int n1 = 0;
int n2 = 1;

yield return 1;
while (true)
{
int n = n1 + n2;
n1 = n2;
n2 = n;
yield return n;
}
}

long result=0;

foreach (int i in Fibonacci().TakeWhile(i => i<4000000).Where(i % 2 == 0))
{
result+=i;
}
Console.WriteLine(result);

在寻找答案之前,我决定自己尝试一下,并想出了这个(请告诉我为什么这是解决这个问题的好方法或坏方法):

我在类里面写它是因为我可以在未来为类添加更多内容,而不仅仅是解决一个斐波那契问题。

class Fibonacci
{
private int prevNum1 = 1;
private int prevNum2 = 2;
private int sum = 0;

public int GetSum(int min, int max)
{
prevNum1 = min;
prevNum2 = prevNum1 + prevNum1;
if (prevNum1 % 2 == 0)
{
sum += prevNum1;
}
if (prevNum2 % 2 == 0)
{
sum += prevNum2;
}
int fNum = 0;
while (prevNum2 <= max)
{
fNum = prevNum1 + prevNum2;
if (fNum % 2 == 0)
{
//is an even number...add to total
sum += fNum;
}
prevNum1 = prevNum2;
prevNum2 = fNum;

}

return sum;
}

}

Fibonacci Fib = new Fibonacci();
int sum = Fib.GetSum(1, 4000000);

Console.WriteLine("Sum of all even Fibonacci numbers 1-4,000,000 = {0}", sum);

同样,我正在寻找关于为什么这是解决此问题的好方法或坏方法的答案。还有为什么第一个解决方案无法编译。我是一名初级程序员,正在努力学习。谢谢!

最佳答案

有了这个它必须编译:

foreach (int i in Fibonacci().TakeWhile(i => i < 4000000).Where(i => i % 2 == 0))
{
result += i;
}

代码无法编译的问题是错误的 lambda 表达式,它是:

.Where(i % 2 == 0)

但必须是

.Where(i => i % 2 == 0)

关于c# - 偶数的斐波那契数列和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11856419/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com