1 minute read

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.

Attacking this problem in using brute force, I create a left and right ints, to hold 1 and 2 respectively, I use these to walk along the fibonacci sequence.

To count along the fibonacci sequence I add the left and right together, and shift them leftwards, until I reach the desired upper limit. On each sequence number, I check if it is even and add to a total if it is.

Here is my solution using Java

public class Problem2
{
    public static void main(String[] args)
    {
        System.out.println(execute(4000000));
    }


    public static int execute(int upperLimit)
    {
        // since we start with 1 & 2, we can assume result always starts from 2, as it's even
        int result = 2;
        int left = 1;
        int right = 2;

        while (left + right < upperLimit)
        {
            int temp = left + right;
            left = right;
            right = temp;
            if (right % 2 == 0)
            {
                result += right;
            }
        }

        return result;
    }
}

The answer is 4613732