This repository was archived by the owner on Apr 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem037.py
More file actions
60 lines (44 loc) · 1.32 KB
/
Copy pathproblem037.py
File metadata and controls
60 lines (44 loc) · 1.32 KB
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
52
53
54
55
56
57
58
59
60
"""
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 math import log10
from prime import Primes
def truncate_from_right(number):
"""
>>> list(truncate_from_right(1234))
[123, 12, 1]
"""
while number > 10:
number = number / 10
yield number
def truncate_from_left(number):
"""
>>> list(truncate_from_left(1234))
[234, 34, 4]
"""
while number > 10:
number = number % (10 ** int(log10(number)))
yield number
def main():
"""
>>> main()
748317
"""
primes = Primes(10 ** 6)
truncatable_prime = []
for prime in primes:
if not all([n in primes for n in truncate_from_right(prime)]):
continue
if not all([n in primes for n in truncate_from_left(prime)]):
continue
truncatable_prime.append(prime)
print(sum(truncatable_prime) - sum([2, 3, 5, 7]))
if __name__ == "__main__":
import doctest
doctest.testmod()