The second
Project Euler problem was another simple one:
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.
I created a few variables to store the elements in the Fibonacci sequence and worked my way up while summing the total of all the even elements below 4 million:
<?
/******************************************************************
* ProjectEuler.net * Problem 2 * 2010-05-31 * Martin Caine *
******************************************************************/
$total = 0;
// store 3 numbers in the sequence
$first = 0;
$second = 1;
$third = 2;
// while the last element is less than or equal to 4 million
while( $third <= 4000000 )
{
// check for even-ness and add to total
if( ($third/2) == (int)($third/2) )
{
$total += $third;
}
// calculate the next numbers int he sequence
$first = $second;
$second = $third;
$third = $first+$second;
}
echo $total;
?>
If you found this post helpful please leave a comment below: