Python Implementation of Problem 37
View source code here on GitHub!
Includes
is_primes()
Problem Solution
Project Euler Problem 37
I was surprised how fast my brute-force solution went, but it worked
Problem:
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.
1"""
2Project Euler Problem 37
3
4I was surprised how fast my brute-force solution went, but it worked
5
6Problem:
7
8The number 3797 has an interesting property. Being prime itself, it is possible
9to continuously remove digits from left to right, and remain prime at each
10stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797,
11379, 37, and 3.
12
13Find the sum of the only eleven primes that are both truncatable from left to
14right and right to left.
15
16NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
17"""
18from .lib.primes import is_prime, primes
19
20
21def main() -> int:
22 answer = count = 0
23 for p in primes():
24 if count == 11:
25 break
26 elif p < 10:
27 continue
28 else:
29 right = left = p
30 while is_prime(right):
31 right = right // 10
32 if right != 0:
33 continue
34 while is_prime(left):
35 x = 10
36 while x < left:
37 x *= 10
38 left %= x // 10
39 if left != 0:
40 continue
41 print(p)
42 answer += p
43 count += 1
44 return answer