Prime permutations (Euler Problem 49)

Back to overview.

https://projecteuler.net/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?

In [20]:
def sieve_of_eratosthenes(number):
    primes = []
    prospects = [n for n in range(2, number)]
    while prospects:
        p = prospects[0]
        prospects = [x for x in prospects if x % p != 0]
        primes.append(p)
        if p * p > number:
            break
    return primes + prospects

ps = [p for p in sieve_of_eratosthenes(10000) if p > 1000]
In [21]:
d = {}
for p in ps:
    s = "".join(sorted(str(p)))
    try:
        d[s].append(p)
    except KeyError:
        d[s] = [p]
        
pss = [value for key, value in d.items() if len(value) >= 3]
In [48]:
def find_increasing_sequence(xs):
    deltas = [(xs[j] - xs[i], i, j)
        for i in range(0, len(xs) - 1)
        for j in range(i + 1, len(xs))
    ]
    d = {}
    for delta, i, j in deltas:
        if delta in d and d[delta][-1] == i:
            d[delta].append(j)
        else:
            d[delta] = [i, j]
    for delta, sequence in d.items():
        if len(sequence) == 3:
            return [xs[index] for index in sequence]
    return []

s = [find_increasing_sequence(ps) for ps in pss if find_increasing_sequence(ps)]
print(s)
[[1487, 4817, 8147], [2969, 6299, 9629]]
In [49]:
s = int("".join(map(str, s[1])))
assert(s == 296962999629)
print(s)
296962999629

Congratulations, the answer you gave to problem 49 is correct.

You are the 49654th person to have solved this problem.

Nice work, failx, you've just advanced to Level 2 . 46903 members (5.43%) have made it this far.

This problem had a difficulty rating of 5%. The highest difficulty rating you have solved remains at 5%.

In [ ]: