Project Euler Problem 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, …

Find the sum of all the even-valued terms in the sequence which do not exceed four million.

PHP Script

<?php
$i = 1;
$num[0] = '1';
while($i < 100) {
	$num[$i] = $num[$i - 2] + $num[$i - 1];
	if($num[$i] > 4000000) {
		unset($num[$i]);
		$i = 100;
	} else {
		if($num[$i] % 2 == 0) {
			$sum += $num[$i];
		}
		$i++;
	}
}
echo $sum;
?>

This script is pretty simple. It runs until the number in the sequence is over 4000000. For each number, it checks if it’s even, or divisible by two. If so, the number is added to the total sum.

Leave a Reply

Your email address will not be published.