Java program to find the sum of the even-valued terms in the Fibonacci sequence whose values do not exceed 4 million

This is another problem taken from Project Euler. Link.

The problem:

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.

So basically we have to find the sum of all even numbers in the Fibonacci sequence within a limit of four million (4000000).
The logic behind this program is simple, we will keep doing addition until our limit reaches 4,000,000. There is just one optimization to the process. If you observe carefully, every third number in the Fibonacci sequence is an even number. So we blindly add every third number in the sequence. This reduces a lot of processing time.

We will be using the datatype BigInteger in our program as we will be dealing with massive numbers.
BigInteger class can be found in java.math.*; package.
Some pointers about BigInteger datatype:
We cannot use the arithmetic or logical operators with the BigInteger datatype. Instead, we use the various methods provided in the package which are as follows. We will be focusing only on the methods used in this program.

add() : To add two BigIntegers.

Syntax:

The above line adds num1 and num2 and stores its value in result.
compareTo(): Used to compare to BigIntegers.

Syntax:

The above line compares num1 and num2. If num1 > num2, result is assigned a positive number. If num1 == num2, result is assigned 0. If num1 < num2, result is assigned a negative number.

Output:
Output project euler problem 2

Tested in Eclipse

The following two tabs change content below.