Sudal's Garage

Project Euler 41 본문

Programming/Project Euler - python

Project Euler 41

_Sudal 2019. 4. 3. 05:00

Question: 


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?

문제:


n 자리 팬디지털 수는 1부터 n까지 정확히 한 번씩만 써서 만든 수를 말한다. 예를 들어 2143은 4자리 팬디지털 수이면서 소수인 숫자이다.

가장 큰 n 자리 팬디지털 소수를 구하여라.


Solution:


from itertools import permutations
from sympy import isprime
import time

nums = '987654321'

def getlen(n):
    return len(list(str(n)))

def check_pandi(n):
    for i in range(1,getlen(n) + 1):
        if str(i) not in list(str(n)):
            return False
    return True

result = 0
start = time.time()

for j in [9,8,7,6,5,4,3,2,1]:
    for i in permutations(nums,j):
        num = ''.join(list(i))
        if isprime(num):
            if check_pandi(num):
                if result < int(num):
                    result = int(num)
                    break
    if result is not 0:
        break
                            
print("""The biggest pandigital prime: {0}
Found in ... {1:.2f}s      
""".format(result,time.time() -start ))


n= 9 일 때 부터 찾으며 pandigital이 판별되면 loop을 break했다.

1.6초 걸렸다.




'Programming > Project Euler - python' 카테고리의 다른 글

Project Euler 43  (0) 2019.04.05
Project Euler 42  (0) 2019.04.04
Project Euler 40  (0) 2019.04.02
Project Euler 39  (0) 2019.04.01
Project Euler 38  (0) 2019.03.31