0

斐波那契数列中的每个新项都是通过添加前两项来生成的。从 1 和 2 开始,前 10 个术语将是:

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

求序列中所有不超过四百万的偶数项之和。

        Int64[] Numeros = new Int64[4000005];
        Numeros[0] = 1;
        Numeros[1] = 2;

        Int64 Indice = 2;
        Int64 Acumulador = 2;

        for (int i = 0; i < 4000000; i++)
        {
            Numeros[Indice] = Numeros[Indice - 2] + Numeros[Indice - 1];

            if (Numeros[Indice] % 2 == 0)
            {
                if ((Numeros[Indice] + Acumulador) > 4000000)
                {
                    break;
                }
                else
                {
                    Acumulador += Numeros[Indice];
                }
            }

            Indice++;
        }

        Console.WriteLine(Acumulador);
        Console.ReadLine();

我的程序没有按我猜的那样运行,因为在 Project Euler 上他们说我的答案不正确。也许我忽略了一些东西。有什么帮助吗?

4

2 回答 2

2

这条线

if ((Numeros[Indice] + Acumulador) > 4000000)

正在检查总和是否大于 4MM。您需要检查项 (Numeros[Indice]) 是否大于 4MM。所以把它改成这个......

if (Numeros[Indice] > 4000000)

可能是一个很好的起点。

于 2009-09-06T14:30:49.360 回答
0

而且你在for循环中的测试条件也是无用的..i永远不会达到4000000的值。只是一个

while(1){
//code
}

也可以,不需要,i因为你从不使用它

于 2009-09-06T14:35:09.960 回答