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?


Idea

Naive solution. Machine helps calculation.

Iterate through, get digits permuations, filter prime ones, check if the permutation sequence is increasing sequence.


In [1]:
from math import sqrt
from itertools import permutations
from functools import reduce
In [2]:
def is_prime(n):
    if n % 2 == 0:
        return False
    return all((n % d for d in range(3, int(sqrt(n))+1, 2)))
In [3]:
is_prime(1487)
Out[3]:
True
In [4]:
def combine_digits(digits):
    return reduce(lambda n, i: n*10+i, digits, 0)
In [5]:
combine_digits((1,2,3))
Out[5]:
123
In [6]:
def get_digits_permutaions(n):
    digits = map(int, str(n))
    p = permutations(digits, len(str(n)))
    return map(combine_digits, p)
In [7]:
list(get_digits_permutaions(123))
Out[7]:
[123, 132, 213, 231, 312, 321]
In [8]:
def get_prime_digits_permutaions(n):
    return filter(is_prime, get_digits_permutaions(n))
In [9]:
list(get_prime_digits_permutaions(1487))
Out[9]:
[1487, 1847, 4817, 4871, 8147, 8741, 7481, 7841]
In [10]:
def get_increasing_sequence(sequence):
    if len(sequence) < 3:
        return []
    substract = lambda n, seq: [s-n for s in seq if s > n]
    divide = lambda d, seq: [s / d for s in seq if s >= d]
    sorted_sequence = sorted(sequence)
    for n ,substract_sequence in ((n, substract(n, sorted_sequence)) for n in sorted_sequence):
        for d in substract_sequence:
            divided_seq = divide(d, substract_sequence)
            if len(set(divided_seq).intersection(set([1.0, 2.0]))) == 2:
                return [n + d * i for i in range(3)]
In [11]:
get_increasing_sequence(list(get_prime_digits_permutaions(1487)))
Out[11]:
[1487, 4817, 8147]
In [12]:
def solve():
    result = set()
    for i in range(1000, 10000):
        seq = get_increasing_sequence(list(get_prime_digits_permutaions(i)))
        if seq and all(map(lambda n: len(str(n)) == 4, seq)):
            result.add(tuple(sorted(seq)))
    assert len(result) == 2
    print(result)
    return [''.join(map(str, seq)) for seq in result]
In [13]:
solve()
{(2969, 6299, 9629), (1487, 4817, 8147)}
Out[13]:
['296962999629', '148748178147']