Duncan's blog

October 17, 2014

Project Euler: problem 52 (PHP) – Permuted multiples

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

52I previously completed this Project Euler puzzle about 6 years ago, using ColdFusion, although I never blogged about it at the time.  This is my approach using PHP as a simple practical exercise for myself, and I’d appreciate any feedback on my PHP code.

Problem 52:

It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.

Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.

Here’s my code, taking basically the same approach as I did with the ColdFusion, although I think this executes much quicker:

$smallestInteger = 1;

while (true) {
	$identicalDigits = true;
	$originalDigits = str_split($smallestInteger);

	foreach (range(2,6) as $multiplier) {
		// work out the multiples of x 
		$multiple = $smallestInteger * $multiplier;
		$newDigits = str_split($multiple);

		// compare this array to the previous one 
		if (count(array_diff($newDigits, $originalDigits)) != 0) {
			$identicalDigits = false;
	// did we get out of the inner loop with two identical arrays? 
	if ($identicalDigits) {

echo $smallestInteger;

So I loop until finding the integer where the digits in x, 2x, 3x, 4x, 5x and 6x are identical.  I get the multiple of the number I’m currently looping over, turn its digits into an array.  I then have an inner loop from 2 to 6, checking if the digits of each multiple of my current number are identical to that number’s digits.


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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: