project-euler/118_pandigital_prime_sets.py

47 lines
979 B
Python
Raw Normal View History

2023-03-26 17:35:02 +02:00
#!/usr/bin/env python3
def primes(n):
sieve = [True] * n
for p in range(2, n):
if not sieve[p]:
continue
for i in range(p**2, n, p):
sieve[i] = False
return [False]*2 + sieve[2:]
sieve = primes(10**7)
def is_prime(n):
if n >= 10**7:
return heuristic(n)
return sieve[n]
def heuristic(n):
for i in range(2, int(n**0.5)+1): #slow and lazy
if sieve[i] and n%i==0:
return False
return True
def num(digs = set(range(1,10)), n=0, id=[]):
c = 0
for d in [i for i in digs if i>n]:
c += dig(digs-{d}, d, d, id)
return c
def dig(digs, n, p, id):
c = check(p, digs, n, id)
for d in digs:
c += dig(digs-{d}, n, 10*p + d, id)
return c
def check(p, digs, n, id):
if len(digs) > 0 and max(digs) < n:
return 0
if not is_prime(p):
return 0
if len(digs) == 0:
return 1
return num(digs, n, id)
print(num())