Duncan's blog

September 19, 2014

Project Euler: problem 1 (PHP) – Multiples of 3 and 5

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

No 1I 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.

Problem 1:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

So not too tricky to start with:

<?php 
$sum = 0;

for ($i = 1; $i < 1000; $i++) {
	if ($i % 3 == 0 || $i % 5 == 0) {
		$sum += $i;
	}
}

echo $sum;
?>

The only thing I really noticed was that I could have used fmod(x, y) instead of x % y == 0 to calculate the modulus values, although I didn’t see any benefit in doing so at this point, with such small integers.  However it wasn’t long before I had to do so (in the third Project Euler puzzle).

3 Comments »

  1. […] without further ado, here’s the first Project Euler puzzle, a load more will hopefully […]

    Pingback by Project Euler redux | Duncan's blog — September 19, 2014 @ 8:04 am | Reply

  2. Something that was pointed out to me early in the piece during my travails into PHP… as a general rule, don’t close your PHP block (“?>”) if it’s the last thing in the file: http://stackoverflow.com/questions/4410704/why-would-one-omit-the-close-tag.

    Comment by dacameron — September 19, 2014 @ 10:31 am | Reply

    • Cool, I’d read this in the PSR-2 coding standard, but didn’t really understand why. I’ll make sure and leave it out from now on!

      Comment by duncan — September 19, 2014 @ 10:43 am | Reply


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

Create a free website or blog at WordPress.com.

%d bloggers like this: