Solution to problem 37
This commit is contained in:
parent
44ee008454
commit
c4a8283576
57
src/Python/Problem037.py
Normal file
57
src/Python/Problem037.py
Normal file
@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Created on 09 Apr 2021
|
||||
|
||||
@author: David Doblas Jiménez
|
||||
@email: daviddoji@pm.me
|
||||
|
||||
Solution for problem 37 of Project Euler
|
||||
https://projecteuler.net/problem=37
|
||||
"""
|
||||
|
||||
from itertools import product
|
||||
from utils import timeit, is_prime
|
||||
|
||||
|
||||
|
||||
@timeit("Problem 37")
|
||||
def compute():
|
||||
"""
|
||||
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.
|
||||
"""
|
||||
|
||||
primes, ans = [], 0
|
||||
for i in range(2,7):
|
||||
candidates = product([1,2,3,5,7,9], repeat=i)
|
||||
for t in candidates:
|
||||
primes.append(''.join([str(d) for d in t]))
|
||||
|
||||
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
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
print(f"Result for Problem 37: {compute()}")
|
Loading…
x
Reference in New Issue
Block a user