Files
contests/037/main.py

53 lines
1.3 KiB
Python

'''
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.
'''
import math
import numpy as np
def sieve(n):
assert n > 1
ns = [True] * n
for i in range(2, math.ceil(np.sqrt(n))):
if ns[i]:
j = pow(i, 2)
while j < n:
ns[j] = False
j = j + i
return [i for i,val in enumerate(ns) if val][2:]
def isTruncable(n, primes):
s = str(n)
for i in range(len(s)):
if int(s[:i+1]) not in primes or int(s[i:]) not in primes:
return False
return True
def main():
print("Hello this is Patrick")
primes = set(sieve(10000000))
truncs = []
i = 11
while len(truncs) < 11:
if isTruncable(i, primes):
truncs.append(i)
print(truncs)
i += 2
print(f"Trunc sum: {sum(truncs)}")
if __name__ == "__main__":
main()