Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #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.
- def isPrime(n):
- '''check if integer n is a prime'''
- if n < 2:
- return False
- # range starts with 2 and only needs to go up the square-root of n
- for x in range(2, int(n**0.5)+1):
- if n % x == 0:
- return False
- return True
- def isTruncPrime(n):
- if n < 10:
- return False
- numStr = str(n)
- while len(numStr) > 1:
- numStr = numStr[1:]
- if not isPrime(int(numStr)):
- return False
- numStr = str(n)
- while len(numStr) > 1:
- numStr = numStr[:len(numStr)-1]
- if not isPrime(int(numStr)):
- return False
- return True
- TruncPrimesList = []
- i = 3
- while len(TruncPrimesList) < 11:
- if isPrime(i) and isTruncPrime(i):
- TruncPrimesList.append(i)
- i += 2
- count = 0
- for i in TruncPrimesList:
- count += i
- print count
Advertisement
Add Comment
Please, Sign In to add comment