Friday, May 29, 2015

Project Euler #49 - 자리바꿈 소수

프로젝트 오일러 49번 - prime permutations
4자리 소수 중 3330, 6660을 더해도 소수이고 이 세 소수가 각 자리수의 자리바꿈인 경우가 딱 두 가지 있다. 하나는 1487, 다른 것은?

4자리 소수를 찾고.. 그냥 하면 되는 문제

def rwh_primes1(n):
    # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
    """ Returns  a list of primes < n """
    sieve = [True] * (n/2)
    for i in xrange(3,int(n**0.5)+1,2):
        if sieve[i/2]:
            sieve[i*i/2::i] = [False] * ((n-i*i-1)/(2*i)+1)
    return [2] + [2*i+1 for i in xrange(1,n/2) if sieve[i]]

pn = rwh_primes1(10000)

for p in [n for n in pn if n > 1000 and n < 3330]:
    if p + 3330 in pn and p + 6660 in pn:
        p2, p3 = p + 3330, p + 6660
        if set(`p`) == set(`p2`) == set(`p3`) and p != 1487:
            print `p`+`p2`+`p3`
            break


No comments: