Problem 37
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.
# 一个素数如果从左右两边依次去掉一个数字后还是素数,就满足条件,求全部的这样的素数的和。
def struct(n):
string = '1379'
result = []
if n == 0:
return ' '
for i in string:
for j in struct(n-1):
temp = i + j
result.append(temp.strip())
return result
def change(string):
lst = [string]
for i in range(1,len(string)):
substr1 = string[i:]
lst.append(substr1)
substr2 = string[:i]
lst.append(substr2)
return lst
def isprime(n):
if n <= 1:
return False
for i in range(2,int(n**0.5+1)):
if n % i == 0:
return False
return True
lst2 = [23, 53]
for i in range(2,7):
for j in struct(i):
for s in change(j):
if not isprime(int(s)):
break
else:
lst2.append(int(j))
if len(lst2) == 11:
print(sum(lst2))
break