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

<?php
$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;
break;
}
}
// did we get out of the inner loop with two identical arrays?
if ($identicalDigits) {
break;
}
$smallestInteger++;
}
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.

### Like this:

Like Loading...

*Related*

## Leave a Reply