Duncan's blog

September 23, 2014

Project Euler: problem 5 (PHP) – Smallest multiple

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

5I 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 5:

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?

Code:

<?php
$step = 20;
$factor = $step - 1;
$i = $step;

while (true) {
	if ($i % $factor == 0) {
		if ($factor == 11) {
			break;
		}
		
		$factor--;
		
		$step = $i;
	} else {
		$i += $step;
	}
}

echo $i;


So a simple while loop that I break out of once we get down to 11.

Advertisements

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

Create a free website or blog at WordPress.com.

%d bloggers like this: