Project Euler Solution 49: Prime permutations

In Problem 49: Prime permutations we again have prime numbers and 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?

Since the terms are going to be 3330 apart and also four digits, the range to check is quite small. To check whether they are permutations of each other we can just sort the digits and compare those. Permutations will be equal there. And finally we need to check whether they are all primes. For this we use the is_prime function from Solution 41: Pandigital prime.

Putting it all together results in this sort program:

def solution() -> int:
    for first in range(1111, 9999 - 2 * 3330):
        second = first + 3330
        third = first + 6660
        if (
            sorted(str(first)) == sorted(str(second)) == sorted(str(third))
            and is_prime(first)
            and is_prime(second)
            and is_prime(third)
        ):
            result = int(f"{first}{second}{third}")
            if result != 148748178147:
                return result

We need to skip the one result from the problem statement. And then we get the other one in 1.4 ms. That's fast enough.