Wednesday, December 24, 2014

Problem 002 : Even Fibonacci Numbers

Even Fibonacci numbers

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.
                                                                                                            https://projecteuler.net/problem=2

Problem 2 is about Fibonacci sequence.
Actual Fibonacci sequence starts with 1 and 1 (or, sometimes 0 and 1), but because the index of each term doesn't matter in this problem, we will not worry about that.

This problem is as simple as the first one, so I just want to briefly explain how I solved it.

I set the upper limit as four million as stated, and used while-loop (current term <= limit).
By using two integer f = 1 and s = 1, I started calculating the next term by adding the previous two terms and checked if it is even integer (current term % 2 == 0)

After adding even term to the sum, I assigned f = s and s = current term so that I can reuse the integers in next calculation until the term is greater than the limit, and we will reach the answer.

private static final int LIMIT = 4000000;
 
public static void run()
{
    int f = 1;
    int s = 1;
    int fibo = 0;
    int sum = 0;
    while (fibo <= LIMIT)
    {
        fibo = f + s;
        if (fibo%2 == 0) sum += fibo;
        f = s;
        s = fibo;
    }
    System.out.println(sum);
}

Answer is 4613732
Execution time is 0.8 ms, or 0.0008 seconds
Source code: https://github.com/Ainodyne/Project-Euler/blob/master/Problem002.java


No comments:

Post a Comment