Project Euler | Problem Two

Problem Two

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.

Yet again another mostly bruteforce method ( see a pattern already?). There is however one exception, Instead of storing all of the numbers and getting them later this will use an array ( why didn’t I just use two variables?) with two longs to represent the previous two values.

The solution just adds the two numbers in the array to get the third. It then tests for evens using the modulus operator, if it is even it adds it to the running total. In the cycles out the oldest number and adds in the newly found number.

/**
 *
 * 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.
 * @author syfran
 * @version %I% %U% %G%
 */
package com.syfran.Euler;                                                                                                      

public class ProblemTwo extends AbstractEuler
{
        private long limit = 4000000;        

        public static void main(String[] pie)
        {
                ProblemTwo p = new ProblemTwo();
                p.start();
        }

        public long solve()
        {
                long [] lastTwo = {1L,2L}; // seed it with one and two
                long sum = 3;
                while(limit > lastTwo[1] )
                {
                        long newNum = lastTwo[0] + lastTwo[1];
                        if(newNum % 2 == 0)     // only get the even numbers
                                sum += newNum;
                        lastTwo[0] = lastTwo[1];
                        lastTwo[1] = newNum;
                }

                return sum;
        }
}
Total Runtime: 0ms

( It will get longer in a couple problems)

Optimizations:

None off the top of my head… maybe I’ll come back.. probably not since its only the second problem


Leave a Reply