""" 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? """ from eulertools import prime_gen_dict from itertools import permutations, combinations prime_dict = prime_gen_dict(10000) #Remove the sequence in the example for num in (1487, 4817, 8147): prime_dict.pop(num) found = False prime_lst = [p for p in sorted(prime_dict.keys()) if p > 1000 and p < 10000] for prime in prime_lst: seq = [] for perm in permutations(str(prime), 4): if not perm[0] == '0': num = int(''.join(perm)) if num not in seq and prime_dict.has_key(num): seq.append(num) if len(set(seq)) >= 3: for c in combinations(sorted(seq), 3): if c[2] - c[1] == c[1] - c[0]:
""" The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. """ from eulertools import prime_gen_dict primes = prime_gen_dict(1000000) def is_truncatable(p): if p < 20: return False s = str(p) length = len(s) #If the prime begins or ends with 1 or 9 return False if s[0] in ('1', '9') or s[length-1] in ('1', '9'): return False #If the prime contains 2 or 5, return False if '2' in s[1:] or '5' in s[1:]: return False if any(not primes.has_key(int(s[i:])) for i in xrange(1, length)): return False if any(not primes.has_key(int(s[:j])) for j in xrange(1, length)): return False return True print sum(p for p in primes if is_truncatable(p))