I previously blogged about this Project Euler puzzle 6 years ago, using ColdFusion. This is my approach using PHP as a simple practical exercise for myself, and I’d appreciate any feedback on my PHP code.
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.
A minor clarification in the specification from when I did this last.
<?php $sum = 0; $fibonacci = 1; $old1 = 0; $old2 = 1; while ($fibonacci <= 4000000) { $fibonacci = $old1 + $old2; $old1 = $old2; $old2 = $fibonacci; if ($fibonacci % 2 == 0) { // it's an even number $sum += $fibonacci; } } echo $sum;
Be sure and read my friend and colleague Adam Cameron’s blog article about another way to do the Fibonacci sequence in PHP using generators.
Leave a comment