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?


In [1]:
from euler import gen_lt, gen_prime

In [2]:
def goo(n):
    return reduce((lambda x, y: x + y), sorted(str(n)))

In [3]:
goo(8471)


Out[3]:
'1478'

In [4]:
def foo(n):
    primes = list(filter((lambda x:x >= 10 ** (n - 1)), gen_lt(gen_prime(), 10 ** n)))
    ps = set(primes)
    pp = [goo(p) for p in primes]
    for i in range(len(primes)):
        p1 = primes[i]
        if p1 == 1487:
            continue
        for j in range(i+1, len(primes)):
            if pp[i] != pp[j]:
                continue
            p2 = primes[j]
            p3 = p2 + (p2 - p1)
            if p3 not in ps:
                continue
            if pp[i] == goo(p3):
                # return reduce((lambda x, y: x + y), map(str, (p1, p2, p3)))
                return str(p1) + str(p2) + str(p3)

In [5]:
n = 4
%timeit foo(n)
foo(n)


10 loops, best of 3: 52.4 ms per loop
Out[5]:
'296962999629'