Skip to content

Instantly share code, notes, and snippets.

@jrjames83
Created July 17, 2017 04:21
Show Gist options
  • Save jrjames83/7dffbf993dde6208661f145baceb7660 to your computer and use it in GitHub Desktop.
Save jrjames83/7dffbf993dde6208661f145baceb7660 to your computer and use it in GitHub Desktop.

https://projecteuler.net/problem=41

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? 765 2413

import itertools
def isprime(n):
    """Returns True if n is prime."""
    if n == 2:
        return True
    if n == 3:
        return True
    if n % 2 == 0:
        return False
    if n % 3 == 0:
        return False

    i = 5
    w = 2

    while i * i <= n:
        if n % i == 0:
            return False

        i += w
        w = 6 - w

    return True
# 2 conditions: is pandigital? is prime?
# highest number, infinity? 987654321

# all pd up to 987654321
# all prime numbers up to 987654321


p1 = list(itertools.permutations('987654321'))
p2 = list(itertools.permutations('87654321'))
p3 = list(itertools.permutations('7654321'))
p4 = list(itertools.permutations('654321'))
p5 = list(itertools.permutations('54321'))
p6 = list(itertools.permutations('4321'))
p7 = list(itertools.permutations('321'))

out = p1 + p2 + p3 + p4 + p5 + p6 + p7
len(out)
409110
candidates = [ int("".join(x)) for x in out]
candidates[4434]
981723654
filtered = [x for x in candidates if isprime(x)]
len(filtered)
538
max(filtered)
7652413
data = '987654321'.split()
data.pop(-1)
data
[]
data
[]
len(set(out))
409110
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment