By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Here is the Problem 2 of Project Euler. It requires finding EVEN fibonacci sequence terms till 4 million and adding them up.

As the terms in the Fibonacci sequence grow in magnitude with each consecutive number, we wouldn’t have a lot many number to be added to sum. So an “int” sized variable would be able to hold the sum.

There are two parts of this problem:

1. Finding if the fibonacci sequence. We generate fibonacci sequence as follows:

Starting with two fibonacci numbers,  fibonacciNumber1 = 0, fibonacciNumber2 = 1

nextFibonacciNumber = fibonacciNumber1 + fibonacciNumber 2

2. Checking if the fibonacci number generated is even or not. If its even add it to sum.

if(x%2 == 0)
    sum = sum + x;

Java implementation of above is as follows:


/*PROBLEM: By considering the terms in the Fibonacci
sequence whose values do not exceed four million,
find the sum of the even-valued terms. */
//OUTPUT: 4613732
class AddFibNum{
int sum;
int x=0,y=1;
void findFib(){
int temp = 0;
while(x<4000000){
temp = x + y;
x=y;
y = temp;
findSum();
}
printSum();
}
void findSum(){
if(x%2 == 0)
sum = sum + x;
}
void printSum(){
System.out.println("The sum is :"+sum);
}
}
class Test2{
public static void main(String [] args){
AddFibNum a = new AddFibNum();
a.findFib();
}
}

It can be solved in a much efficient manner by taking into consideration the recursive pattern.
Thanks. Keep Coding.

Leave a Reply

Your email address will not be published. Required fields are marked *