Ascent

Even Fibonacci Numbers

A second introductory problem, this time introducing integer sequences reliant on previous values.

The problem

The Fibonacci sequence is an integer sequence obtained by adding the previous two terms. For the purposes of the euler problem, we are told the first 10 items in this sequence will be:

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

Our problem is to sum the values of all even Fibonacci numbers that do not exceed 4 million.

Approach

The first two terms are listed as "1, 2", so we would be well served by defining an array to hold our values, and initialize it appropriately.

fibonacci = [ 1, 2 ]

Now, with a starting array indexed with 2 values, we can proceed with a basic loop utilizing both previous indices.

fibonacci[ i ] = fibonacci[ i - 2 ] + fibonacci[ i - 1 ]

Lastly, we will need an even/odd test. There are a few ways to do this, one of the easiest being the use of modulus

if( value % 2 ) {
	// This value will be even
} else {
	// This value is odd.
}

Sum and done!

Get the latest posts delivered right to your inbox.
Author image
Written by Ben
Ben is the co-founder of Skyward. He has spent the last 10 years building products and working with startups.