You are on the Home/Other Tutorials/Project Euler/Problem 2 page
Google
Web This Site

Project Euler - Problem 2

More about Project Euler.

Problem description

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.

Solution

The Fibonacci sequence that I am familiar with starts with 0 and 1 (see http://en.wikipedia.org/wiki/Fibonacci_number, for example) yielding 0, 1, 1, 2, 3, 5, 8, 13, ...  The distinction between the 2 series might or might not be important.

I was not sure how to interpret "even-valued terms."  Did it mean numbers in the Fibonacci sequence that were divisible by two or did it mean numbers in positions that were divisible by two.  If the former, than the difference in the start of the sequence was irrelevant.  If the latter, it would mean adding an extra 1 to the desired result (2, 5, 13, etc. given the Project Euler definition of the Fibonacci sequence and 1, 2, 5, 13, etc given the definition that starts with 0).

I decided that the Project Euler folks would not have left this kind of ambiguity in the problem after such a long period of time.  So, I decided to proceed with the assumption that the desired result was the sum of those numbers that themselves were even.

One can easily do this in Excel.

To generate the Fibonacci sequence, enter 0 and 1 in two adjacent cells in a column.  I picked B2:B3.  Then, in B4 enter the formula =B2+B3.  Copy B4 as far down column B as need to generate a number greater than 4,000,000.  That should be in cell B36.  Finally, in some cell, say, C2 enter the array formula =SUM(IF(MOD(B2:B35,2)=0,B2:B35))  To enter an array formula, complete data entry with the combination of CTRL+SHIFT+ENTER and not just the ENTER or TAB key.  If done correctly, Excel will show the formula enclosed in curly brackets { and }.

The VB(A) code is also simple enough and given how "small" the problem is, there would be no performance issues.  So, here it is:

Option Explicit

Sub Euler2()
    Dim Rslt As Long, PrevVal As Long, NextVal As Long, CurrVal As Long
    PrevVal = 0: CurrVal = 1
    Do
        If CurrVal Mod 2 = 0 Then Rslt = Rslt + CurrVal
        NextVal = PrevVal + CurrVal
        PrevVal = CurrVal: CurrVal = NextVal
        Loop Until CurrVal >= 4000000
    Debug.Print Rslt
    End Sub