Solving the Project Euler Problem 2 is simple and I believe it still does not required great processing power to search for the clever algorithms. The description of Problem 2 is:

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.

In the order to find a final sum, first it is necessary to generate the Fibonacci sequence. The sum of the first 2 elements in the sequence creates the third. The loop than go on and the second and the third element create forth , etc.

All we need to do now do is just to check if the newly generated number is dividable by 2. If it is we can sum it up with the rest. The sum is already 2 since we begin by generating the 3rd number (the sum of first 2 elements $a and $b).

So the algorithms goes like this:

- Definition of starting variables.
- Loop for generating +1 bigger number.
- Check if number is dividable by 2.
- If yes, number is summed.
- Output of result.

## PHP:

<?php $sum = 2; $a = 1; $b = 2; $c = null; while ($c < 4000000) { $c = $a + $b; if($c%2 == 0) { $sum += $c; } $a = $b; $b = $c; } echo $sum; ?>

## Java:

public class Project_Euler_Problem_002 { public static void main(String[] args) { System.out.println("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:"); System.out.println("1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …"); System.out.println("Find the sum of all the even-valued terms in the sequence which do not exceed four million."); int sum = 2, a = 1, b = 2, c = 0; while (c < 4000000) { c = a + b; if(c%2 == 0) { sum += c; } a = b; b = c; } System.out.println("\n"+ "Sum is: " + sum);; } }

Hint: While reviewing the algorithm with the solutions of others I notice a difference. This algorithm is based on the Fibonacci sequence starting 1,2,3… not 1,1,2,3.

Pingback: Project Euler Problem 3 - Largest prime factor - CodeKopf.com