Home Project Euler Teaching Projects Gallery

Problem 49: Prime permutations

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?


Algorthim:

Very interesting problem. A lot of components to this problem: we have to check prime condition, check arthimetic condition, and then also check permutations condition.

Luckily, we are given how many digits are in this sequence.

So, let's look at our first condition: Permutatation. How do we determine if two numbers are permutations of one another? My method is to convert the number into a list. So, every digit gets placed into separate box. Then, we sort the number. We take another and do the same thing. Then we place one of the array digit into another array, this makes a 2D array, with 1 row and nth column where n represents number of digits. Python allows us to check if an element is in another list. But since we want to check if an array is in another list, then we can check if the first array is in 2D array: For example, take 1234 and 4321: $$ 3214 -> sorted -> [1, 2, 3, 4] $$ $$ 4321 -> sorted - > [1, 2, 3, 4] $$ We place one of the array into another array $$ [[1, 2, 3, 4]] $$ Then we can check if [1, 2, 3, 4] is an element of this 2D array! BUT we have to make sure the elements are sorted! [1, 2, 3, 4] is not the same as [3, 2, 4, 1]

Next, how do we check of arthimeticity? (is that even a word?) We can make a double for loop, looping the primes generated using sieve. We first pick a prime, then we pick another prime. We first check if they are permutaation of one another which is done above. If that's the case, we find the difference of the two. Since the second for loop generates the bigger prime, we add this difference to this bigger prime and check if this "added bigger prime" is a permutation and a prime!

Code:

Result:

Answer: 296962999629
Runtime: 1.9 seconds