princeofsudan

ProjectEuler#37 Truncatable primes

Mar 29th, 2013
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.29 KB | None | 0 0
  1. #The number 3797 has an interesting property. Being prime itself, it is
  2. #possible to continuously remove digits from left to right, and remain prime
  3. #at each stage: 3797, 797, 97, and 7. Similarly we can work from right to
  4. #left: 3797, 379, 37, and 3.
  5.  
  6. #Find the sum of the only eleven primes that are both truncatable from left
  7. #to right and right to left.
  8.  
  9. #NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
  10.  
  11. def isPrime(n):
  12.     '''check if integer n is a prime'''
  13.     if n < 2:
  14.         return False
  15.     # range starts with 2 and only needs to go up the square-root of n
  16.     for x in range(2, int(n**0.5)+1):
  17.         if n % x == 0:
  18.             return False
  19.     return True
  20.  
  21. def isTruncPrime(n):
  22.     if n < 10:
  23.         return False
  24.     numStr = str(n)
  25.     while len(numStr) > 1:
  26.         numStr = numStr[1:]
  27.         if not isPrime(int(numStr)):
  28.             return False
  29.     numStr = str(n)
  30.     while len(numStr) > 1:
  31.         numStr = numStr[:len(numStr)-1]
  32.         if not isPrime(int(numStr)):
  33.             return False  
  34.        
  35.     return True
  36.  
  37. TruncPrimesList = []
  38. i = 3
  39.  
  40. while len(TruncPrimesList) < 11:
  41.     if isPrime(i) and isTruncPrime(i):
  42.         TruncPrimesList.append(i)
  43.     i += 2
  44.  
  45. count = 0
  46. for i in TruncPrimesList:
  47.     count += i
  48. print count
Advertisement
Add Comment
Please, Sign In to add comment