Project Euler - Problem 2 Solution With PHP

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.

Our second problem gives us a sequence which our teachers forced us to learn at the primary school. The lovely "Fibonacci sequence".

Here is an option to solve this problem in PHP:

$n1 = 1;
$n2 = 2;
$n3 = $n1 + $n2;

$sum = 2;

while ($n3 < 4000000) {
    $n1 = $n2;
    $n2 = $n3;
    $n3 = $n1 + $n2;
    
    if ($n3 % 2 == 0) {
        $sum += $n3;
    }
}

echo $sum;

We already know the first three numbers which create us a pretty nice start point for our tiny calculator. So we define the first three numbers and according to our "hard-coded" data, we define the $sum. The important point is to keep in mind that only the even numbers should be added to the $sum.

In the while loop, we check if the next number of the sequence smaller than 4 million. If it is, we are good to go and check if our second condition passes.

We know that the modulus (%) of even numbers to 2 should result 0. So we write out if statement and all done!

Execution time: 0s

Copyright © Ozan Kurt 2015.

Scroll to Top