# Prime digit replacements (Euler Problem 51)¶

Back to overview.

https://projecteuler.net/problem=51

By replacing the 1st digit of the 2-digit number x3, it turns out that six of the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime.

By replacing the 3rd and 4th digits of 56xx3 with the same digit, this 5-digit number is the first example having seven primes among the ten generated numbers, yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and 56993. Consequently 56003, being the first member of this family, is the smallest prime with this property.

Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit, is part of an eight prime value family.

We start by writing a function that takes a number and returns all possible replacements.

For example 13 will return ["x3", "1x"].

I actually had a version that simply replace even digits at first, but that does not work for 56333 for example, because you want to get 56xx3 and not 56xxx. So basically, we have to search for all combinations for each digit. I should probably document what each list comprehension does or I will never understand it again. Haha.

In [1]:

    from itertools import combinations

    def get_replacements(n):
        n = str(n)
        xss= [[i for i in range(0, len(n)) if n[i] == d]
               for d in "0123456789"]
        xss = [x
               for xs in xss if xs
               for i in range(1, len(xs) + 1)
               for x in combinations(xs, i)]
        xss = ["".join(['x' if i in xs else d for i, d in enumerate(n)])
               for xs in xss]
        return xss

    #assert(get_replacements(13) == ["x3", "1x"])
    print(get_replacements(13))

    ['x3', '1x']

We will use our good old prime generator.

In [2]:

    def is_prime(n, smaller_primes):
        for s in smaller_primes:
            if n % s == 0:
                return False
            if s * s > n:
                return True
        return True

    def prime_generator_function():
        primes = [2, 3, 5, 7]
        for p in primes:
            yield p
        while True:
            p += 2
            if is_prime(p, primes):
                primes.append(p)
                yield p

In [3]:

    replacements = {}
    ps = prime_generator_function()
    for p in ps:
        for r in get_replacements(p):
            try:
                replacements[r].append(p)
                if len(replacements[r]) == 8:
                    print(replacements[r])
                    s = replacements[r][0]
                    p = 100000000000 # We have found a solution so we go home
            except KeyError:
                replacements[r] = [p]
        if p > 1000000:
            break

    [121313, 222323, 323333, 424343, 525353, 626363, 828383, 929393]

In [4]:

    print(s)
    assert(s == 121313)

    121313

In [ ]: