I previously blogged about this Project Euler puzzle nearly 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 49:

*The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another.*

*There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence.*

*What 12-digit number do you form by concatenating the three terms in this sequence?*

Code:

<?php
require 'isPrime.php';
$end = 9999 - (3330 * 2);
function sameDigits($x, $y)
{
$i = 0;
$arrX = str_split($x);
$arrY = str_split($y);
sort($arrX, SORT_NUMERIC);
sort($arrY, SORT_NUMERIC);
return count(array_diff($arrX, $arrY)) === 0;
}
for ($i = 1489; $i <= $end; $i += 2) {
$num2 = $i + 3330;
$num3 = $num2 + 3330;
if (
sameDigits($i, $num2)
&& sameDigits($i, $num3)
&& isPrime($i)
&& isPrime($num2)
&& isPrime($num3)
) {
echo $i . $num2 . $num3;
break;
}
}

Re-using my isPrime function from Problem 3.

Previously in ColdFusion I had an overly-complicated function which took two numbers as arguments, looped over them inserting them to arrays, sorted the arrays, then looped over the arrays to work out if all the digits were identical. In PHP I can simply use str_split() to convert the numbers into arrays, then array_diff() to compare the two arrays. I’ve used count() to check that the ‘diff’ array returned by array_diff is empty, quite probably there’s more efficient ways to do this.

Yet another example of PHP’s inconsistencies; some array functions like *array_diff* are prefixed with ‘array_’, some like *sort* are not, with no obvious rhyme or reason behind it that I can discern.

### Like this:

Like Loading...

*Related*

Is it part of the requirement that the sequence needs to be – specifically – 3330 apart? Or am I missing some quality of 3330 that makes it essential to the rest of the requirement?

—

Adam

Comment by dacameron — October 16, 2014 @ 9:33 pm |

yeah, the way the question’s worded is vague about this, maybe deliberately so. When I originally did this I opted for the simpler assumption, which proved to be correct. Is 3330 the only 4 digit number that this works with though? It’s ‘unusual’, not unique.

Comment by duncan — October 16, 2014 @ 10:11 pm |