Prime pair sets
Problem 60
The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.
Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.
from tools import primes_sieve2, is_prime
def check_ab_ba_is_prime(a, b):
if a == b:
return False
ab = int('%d%d' % (a, b))
ba = int('%d%d' % (b, a))
return is_prime(ab) and is_prime(ba)
def prime_pairs():
"""
Using cached dict with prime numbers for keys and possible sets as values of primes that had been discovered so far.
For every new prime, it generates a list of primes that are created by concatenating them with the new prime.
For every prime in the list of positives, it checks all the contained sets for being a subset of the set of positives.
If it is a subset, then the set containing the union of the set and the current prime is added to the set of sets for the index and for the new prime.
Result is the first generated set with a length of five.
"""
cache = {}
p_gen = primes_sieve2(10000)
# discard 2
p = p_gen.next()
p = p_gen.next()
cache[p] = set([frozenset([p])])
# discard 5
p = p_gen.next()
while True:
p = p_gen.next()
possibles = set([i for i in cache.keys() if check_ab_ba_is_prime(p, i)])
p_set = frozenset([p])
gen_sets = set([p_set])
for i in cache.keys():
if i in possibles:
new_sets = set()
for s in cache[i]:
if s <= possibles:
sp = s | p_set
if len(sp) == 5:
return sp
new_sets.add(sp)
gen_sets.add(sp)
cache[i] |= new_sets
cache[p] = gen_sets
def run():
result = prime_pairs()
return sum(result)