Duncan's blog

September 20, 2014

Project Euler: problem 2 (PHP) – Even Fibonacci numbers

Filed under: PHP,Project Euler — duncan @ 8:00 am

Spiral cactusI 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.

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, …

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 »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: