Solution to problem 37

This commit is contained in:
David Doblas Jiménez 2021-09-07 15:19:47 +02:00
parent 4985501d1a
commit 2213718a30

View File

@ -9,10 +9,15 @@ Solution for problem 37 of Project Euler
https://projecteuler.net/problem=37 https://projecteuler.net/problem=37
""" """
from itertools import product from utils import timeit, list_primes, is_prime
from utils import timeit, is_prime
def is_truncatable_prime(number):
num_str = str(number)
for i in range(1, len(num_str)):
if not is_prime(int(num_str[i:])) or not is_prime(int(num_str[:-i])):
return False
return True
@timeit("Problem 37") @timeit("Problem 37")
def compute(): def compute():
@ -27,28 +32,12 @@ def compute():
NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
""" """
ans = 0
primes, ans = [], 0 primes = list_primes(1_000_000)
for i in range(2,7): # Statement of the problem says this
candidates = product([1,2,3,5,7,9], repeat=i) for number in primes[4:]:
for t in candidates: if is_truncatable_prime(number):
primes.append(''.join([str(d) for d in t])) ans += number
for p in primes:
trunc = True
if not is_prime(int(p)):
trunc = False
continue
for i in range(1, len(p)):
if not is_prime(int(p[i:])):
trunc = False
break
if not is_prime(int(p[:i])):
trunc = False
break
if trunc:
ans += int(p)
return ans return ans