Skip to content
Advertisement

Finding the sum of even valued terms in Fibonacci sequence

JavaScript

My algo:

  1. If I take first 2 numbers as 0, 1; the number that I find first in while loop will be an odd number and first of Fibonacci series.
  2. This way I calculate the even number and each time add the value of even to total.
  3. If value of even is greater than 4e6, I break from the infinite loop.

I have tried so much but my answer is always wrong. Googling says the answer should be 4613732 but I always seem to get 5702886

Advertisement

Answer

Basically what you’re doing here is adding every second element of the fibonacci sequence while the question asks to only sum the even elements.

What you should do instead is just iterate over all the fibonacci values below 4000000 and do a if value % 2 == 0: total += value. The % is the remainder on division operator, if the remainder when dividing by 2 equals 0 then the number is even.

E.g.:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement