-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path037.py
51 lines (39 loc) · 1.06 KB
/
037.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""
Project Euler 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.
"""
from utils import gen_primes
from math import log10
def valid_property(n):
copy_n = n
while copy_n:
if copy_n not in primes:
break
copy_n //= 10
if copy_n > 0:
return False
digits = int(log10(n))
while n:
if n not in primes:
break
n %= 10 ** digits
digits -= 1
return n == 0
primes = set()
counter = 0
sum_ = 0
for prime in gen_primes():
primes.add(prime)
if prime > 10 and valid_property(prime):
counter += 1
sum_ += prime
if counter == 11:
break
print(sum_)