Even Fibonacci Sums

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, …

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

This one was tricky. I used four variables to track the current number in iteration, the last number to add to the current number, an accumulator to add up the even fibonacci numbers and a temp variable to save the current number.

So…

while current number is less than 4,000,000

temporary variable gets current number (because we need to transform the current number but also save it into the trailer)

check if current number modulo 2 is zero (is current number even)

if yes, add current number to accumulator

 

current number plus the trailer value (initialized to 1 to begin)

trailer gets temporary variable

continue loop

 

return accumulator

 

This yields the correct result!

 

 

Leave a comment