# Find the sum of all Truncatable primes below N in Python

Suppose we have a given integer N; we have to find the sum of all Truncatable primes less than N. As we know the truncatable prime is a number which is left-truncatable prime (if the leading "left" digit is successively removed, then all resulting numbers are treated as prime) as well as right-truncatable prime (if the last "right" digit is successively removed, then all the resulting numbers are treated as prime). An example of truncatable prime is 9137 as this is lefttruncatable prime because 9137, 137, 37 and 7 are primes. Hence 9137 is a truncatable prime.

So, if the input is like N = 55, then the output will be 130 as (2 + 3 + 5 + 7 + 23 + 37 + 53) =

To solve this, we will follow these steps −

• N := 1000005

• prime := a list of size N and fill with True

• Define a function sieve() . This will take

• prime[1] := False, prime[0] := False

• for i in range 2 to N, do

• if prime[i] is same as True, then

• for j in range i * 2 to N, update in each step by i, do

• prime[j] := False

• From the main method, do the following −

• sum := 0

• for i in range 2 to n, do

• current := i

• f := True

• while current is non-zero, do

• if prime[current] is False, then

• f := False

• come out from the loop

• current := current / 10

• current := i

• power := 10

• while quotient of (current / power) is non-zero, do

• if prime[current mod power] is False, then

• f := False

• come out from the loop

• power := power * 10

• if f is True, then

• sum := sum + i

• return sum

## Example

Let us see the following implementation to get better understanding −

Live Demo

N = 1000005
prime = [True for i in range(N)]
def sieve():
prime[1] = False
prime[0] = False
for i in range(2, N):
if (prime[i]==True):
for j in range(i * 2, N, i):
prime[j] = False
def get_total_of_trunc_primes(n):
sum = 0
for i in range(2, n):
current = i
f = True
while (current):
if (prime[current] == False):
f = False
break
current //= 10
current = i
power = 10
while (current // power):
if (prime[current % power] == False):
f = False
break
power *= 10
if f:
sum += i
return sum
n = 55
sieve()
print(get_total_of_trunc_primes(n))

## Input

55

## Output

130