-
Notifications
You must be signed in to change notification settings - Fork 0
/
problem-037.py
50 lines (40 loc) · 1.5 KB
/
problem-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
### Problem 37 - Truncatable Primes
###----------------------------------------------------------------------------------------------------------------------------------
### 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.
### Solution
# Function to determine if prime. n:int -> boolean
def isPrime(n):
if n < 2:
return False
elif n == 2:
return True
else:
i = 2
while i ** 2 <= n:
if n % i == 0:
return False
i += 1
return True
# Function to determine if trunctable from left. n:int -> boolean
def trunctLeft(n):
num_str = str(n)
for i in range(len(num_str)):
if not isPrime(int(num_str[i:])):
return False
return True
# Function to determine if trunctable from right. n:int -> boolean
def trunctRight(n):
num_str = str(n)
for i in range(len(num_str)):
if not isPrime(int(num_str[0 : (len(num_str) - i)])):
return False
return True
primes = []
current_num = 8
while len(primes) < 11:
if trunctLeft(current_num) and trunctRight(current_num):
primes.append(current_num)
current_num += 1
print("The sum of trunctable primes is: " + str(sum(primes)))