ItGo.me Focus on IT Recommend

Home > Project Euler N2 - Fibonacci algorithm isnt working properly

Project Euler N2 - Fibonacci algorithm isnt working properly

2021腾讯云限时秒杀,爆款1核2G云服务器298元/3年!(领取2860元代金券),
地址https://cloud.tencent.com/act/cps/redirect?redirect=1062

2021阿里云最低价产品入口+领取代金券(老用户3折起),
入口地址https://www.aliyun.com/minisite/goods

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.

        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();

My program isn't functioning as it should be I guess because on Project Euler they say my answer is incorrect. Maybe I'm overlooking something. Any help?

algorithm fibonacci
|
  this question
edited Jan 22 '15 at 17:54 iCodez 82k 18 116 147 asked Sep 6 '09 at 14:20 Sergio Tapia 12.1k 58 139 233 5   For a start, you only need to keep track of the last two numbers. –  Matthew Scharley Sep 6 '09 at 14:25      Do first a check on the upper limit before checking if the number is even. –  ba__friend Sep 6 '09 at 14:35

 | 

2 Answers
2

This line

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

is checking for the sum being greater than 4MM. You need to check that the term (Numeros[Indice]) is greater than 4MM. So changing that to this...

if (Numeros[Indice] > 4000000)

is probably a good place to start.


|
  this answer
answered Sep 6 '09 at 14:30 Jason Punyon ♦ 28.8k 8 78 110

 | 

And also man your test condition in for loop is useless.. i wil never reach the value of 4000000. simply a

while(1){
//code
}

will also do, no need of i as u never use it


|
  this answer
answered Sep 6 '09 at 14:35 sud03r 9,170 13 58 88

 | 

------splitte line----------------------------
Related