Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #We shall say that an n-digit number is pandigital if it makes use of all
- #the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital
- #and is also prime.
- #What is the largest n-digit pandigital prime that exists?
- import itertools
- 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 generatePerm(nDigits):
- #tupleList is sorted asc
- tupleList = list(itertools.permutations(range(1,nDigits+1),nDigits))
- intList = []
- for i in tupleList: #Convert tuples list generated to ints list
- digitStr = ''
- for j in i:
- digitStr += str(j)
- if int(digitStr)%2 != 0: #add to ints list only odd numbers
- intList.append(int(digitStr)) #(evens are not primes)
- return intList
- largest = 0
- for i in range(9,0,-1):
- intList = generatePerm(i)
- for j in range(len(intList)-1,-1,-1): #iterate backwards (list sorted asc)
- if isPrime(intList[j]):
- largest = intList[j]
- break
- if largest != 0:
- break
- print largest
- #Improvement - Not Implemented:
- #only 4 or 7 digit numbers need to be considered.
- #Proof: the sum of the digits is 1+2+3+...+n = n(n+1)/2. It is divisible by 3
- #if n or n+1 are divisible by 3. So only n = 1, 4, 7 are such that n(n+1)/2 is
- #not divisible by 3. 1 can be ignored since 1 is not prime.
- #Source: Project Euler ernacktob solution.
Advertisement
Add Comment
Please, Sign In to add comment