<?php
/*
Problem 2
19 October 2001
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.*/
print "By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
\n";
define('MAX_NUM', 4000001); // thru and including 4 million
define('DIVISOR', 2);
$previous1_term = 1;
$previous2_term = 2;
$sum = 0;
while($previous1_term < MAX_NUM
|| $previous2_term < MAX_NUM)
{
if($previous1_term < MAX_NUM
&& ($previous1_term % DIVISOR) === 0)
{
$sum = $sum + $previous1_term;
print "$previous1_term + ";
}
if($previous2_term < MAX_NUM
&& ($previous2_term % DIVISOR) === 0)
{
$sum = $sum + $previous2_term;
print "$previous2_term + ";
}
$previous1_term = $previous1_term + $previous2_term;
$previous2_term = $previous1_term + $previous2_term;
}
print "
sum: $sum";
?>