# Blog Archives

## Project Euler Problem #2 Solution in Java

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.

/**
* @author Khuram Ali
*/
public class Problem2
{
public static void main(String[] args)
{
int term_1 = 1;
int term_2 = 2;
int term_3 = 0;
int sum = 0;
long MaxTerm = 4000000;

while (term_1 <= MaxTerm)
{
System.out.println (term_1);
if ((term_1 %2) == 0){sum += term_1;}

term_3 = term_1 + term_2;
term_1 = term_2;
term_2 = term_3;
}
System.out.println (“the sum of even value numbers is: “);
System.out.println (sum);
}
}

## Project Euler: Problem #2 solution in C++

`/**(From:http://projecteuler.net/index.php?section=problems&id=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.

Solution:*/

#include <iostream>

using namespace std;

int main()
{

int term_1 = 1;
int term_2 = 2;
int term_3 = 0;
int MaxTerm = 0;
int sum = 0;

cout<< “This Program lists the Fibonacci sequence. Please enter the Max number you want to have sequence:” << endl;

cin >> MaxTerm ;

while (term_1 <= MaxTerm)
{
cout<< term_1 << endl;
if ((term_1 %2) == 0){sum += term_1;}

term_3 = term_1 + term_2;
term_1 = term_2;
term_2 = term_3;

}
cout << “the sum of even value numbers is: “<< sum << endl;
}