Project Euler – Problem 2

This is the second post in my Project Euler series (if series is the right word). The first problem is here.

Problem 2

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 problem is near and dear to my heart for a few reasons. When my lovely wife was just a little girl, she had trouble sleeping, so her father basically taught her the Fibonacci sequence and told her to just keep adding numbers together until she fell asleep. Additionally, when I took my discrete math course, we talked about the Fibonacci sequence A LOT. And finally, I’m not sure why, but at a young age I decided to take some online IQ test and there was a problem that I found very interesting. It was something along the lines of:

If you add the numbers 1 through 5 together the answer will be odd.

If you add the numbers 1 through 20 together, will the answer be even or odd.

Now, for anyone that knows, you can always solve this problem the quick and dirty way:

then multiply 21 by the number of pairs there are (10) and you’ll wind up with 210. Nice, quick, easy and to the point. But that’s not how my little mind worked. It worked a little more like this:

By this simple logic, the only way to end up with an odd number is to add it to an even one. This reduces the whole problem down to one simple question: is there an even amount of odd numbers between 1 and 20?

The answer is that there are an even number of odd numbers between 1 and 20. I believe this is a good algorithm for determining the number of odd numbers in a range. Apparently my 8 year old brain was smarter than adult me, because adult me had to look it up.

At any rate, that’s not the import part. What’s important is odd + even is the only way to get an odd number out.

The Fibonacci sequence being 1, 1, 2, 3, 5, 8... Follows a grand pattern – odd + odd, odd + even, even + odd, repeat. By taking advantage of this pattern, we don’t have to look at every number in the sequence. We can already determine that every 3rd number will be even.

Of course, we could have just generated every value of the Fibonacci sequence and checked it’s evenness, but this way is far more clever.

Leave a Reply

Your email address will not be published. Required fields are marked *