Truncatable primes : Problem 37
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.
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.
Problem Source : Euler Project
Python Code : Truncatable Prime
import math
def TruncatablePrime():
def checkPrime(numb):
prime = True
if numb == 1:
return False
else:
for i in range(int(math.sqrt(numb))):
i = i+2
if numb%i == 0:
prime = False
break
if numb == 2:
return True
else:
return prime
def reverse(text):
if len(text) <= 1:
return text
return reverse(text[1:]) + text[0]
truncPrimeCount = 0
sumTruncPrimeCount = 0
dummy = 12
while truncPrimeCount < 11:
if checkPrime(dummy) == True:
strnumb = str(dummy)
flag = False
truncPrimeflag = False
for i in range(len(strnumb)-1):
i = i+1
if int(strnumb[i])%2 == 0:
flag = True
break
if flag == False:
strnumbrev = reverse(strnumb)
#print "reverse",strnumbrev
tmpstrleft = ""
tmpstrright = ""
for i in range(len(strnumb)-1):
tmpstrleft = tmpstrleft+strnumb[i]
#print "111*****",tmpstrleft
tmpstrright =(tmpstrright)+strnumbrev[i]
#print "222#####",tmpstrright
if checkPrime(int(tmpstrleft)) == True and checkPrime(int(reverse(tmpstrright))) == True:
truncPrimeflag = True
else:
truncPrimeflag = False
break
if truncPrimeflag == True:
sumTruncPrimeCount = sumTruncPrimeCount + dummy
truncPrimeCount = truncPrimeCount + 1
print "Truncatable Prime[",truncPrimeCount,"]",dummy
dummy = dummy + 1
print "sum of the only eleven primes that are both truncatable from left to right and right to left",sumTruncPrimeCount
TruncatablePrime()
No comments:
Post a Comment