princeofsudan

ProjectEuler#41 Pandigital prime

Apr 5th, 2013
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.59 KB | None | 0 0
  1. #We shall say that an n-digit number is pandigital if it makes use of all
  2. #the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital
  3. #and is also prime.
  4.  
  5. #What is the largest n-digit pandigital prime that exists?
  6.  
  7. import itertools
  8.  
  9. def isPrime(n):
  10.     '''check if integer n is a prime'''
  11.     if n < 2:
  12.         return False
  13.     # range starts with 2 and only needs to go up the square-root of n
  14.     for x in range(2, int(n**0.5)+1):
  15.         if n % x == 0:
  16.             return False
  17.     return True
  18.  
  19. def generatePerm(nDigits):
  20.     #tupleList is sorted asc
  21.     tupleList = list(itertools.permutations(range(1,nDigits+1),nDigits))
  22.     intList = []
  23.     for i in tupleList: #Convert tuples list generated to ints list
  24.         digitStr = ''
  25.         for j in i:
  26.             digitStr += str(j)
  27.         if int(digitStr)%2 != 0: #add to ints list only odd numbers
  28.             intList.append(int(digitStr)) #(evens are not primes)
  29.     return intList
  30.  
  31. largest = 0  
  32. for i in range(9,0,-1):
  33.     intList = generatePerm(i)
  34.     for j in range(len(intList)-1,-1,-1): #iterate backwards (list sorted asc)
  35.         if isPrime(intList[j]):
  36.             largest = intList[j]
  37.             break
  38.     if largest != 0:
  39.         break
  40. print largest
  41.  
  42.  
  43. #Improvement - Not Implemented:
  44. #only 4 or 7 digit numbers need to be considered.
  45. #Proof: the sum of the digits is 1+2+3+...+n = n(n+1)/2. It is divisible by 3
  46. #if n or n+1 are divisible by 3. So only n = 1, 4, 7 are such that n(n+1)/2 is
  47. #not divisible by 3. 1 can be ignored since 1 is not prime.
  48. #Source: Project Euler ernacktob solution.
Advertisement
Add Comment
Please, Sign In to add comment