-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path037 - Truncatable primes.py
53 lines (39 loc) · 1.19 KB
/
037 - Truncatable primes.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
52
53
__author__ = 'Mathias'
import timeit
def primes_sieve(bound):
if bound == 0 or bound == 1:
return 0
a = [True] * bound
a[0] = a[1] = False
for (i, is_prime) in enumerate(a):
if is_prime:
yield i
for index in range(i * i, bound, i):
a[index] = False
def is_truncatable(prime, set):
truncatable = True
left_string = str(prime)[1:]
while len(left_string) > 0:
if {int(left_string)} <= set:
left_string = left_string[1:]
else:
truncatable = False
break
right_string = str(prime)[:-1]
while truncatable and len(right_string) > 0:
if {int(right_string)} <= set:
right_string = right_string[:-1]
else:
truncatable = False
break
return truncatable
start = timeit.default_timer()
primes_list = list(primes_sieve(1000000))
primes_set = set(primes_list)
truncatable_primes = []
while len(truncatable_primes) < 11:
for prime in primes_list:
if prime > 10 and is_truncatable(prime, primes_set):
truncatable_primes.append(prime)
print(sum(truncatable_primes))
print(timeit.default_timer() - start)