Project Euler Problem 037
Statement
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.
Solution
A simple brute-force solution.
from CommonFunctions import find_primes_less_than from itertools import islice, count primes = set(find_primes_less_than(1000000)) def is_truncable(i): if i < 10: return False tmp = str(i) for x in range(len(tmp)): if (int(tmp[x:]) not in primes) or (int(tmp[:x + 1]) not in primes): return False return True if __name__ == '__main__': result = sum(islice(filter(is_truncable, primes), 11)) print("The result is:", result)
The Python file is available for download here.