Solve problem 118.
parent
67526f1978
commit
9c6187f51f
|
@ -0,0 +1,45 @@
|
|||
from itertools import combinations, permutations
|
||||
from lib_prime import is_prime_rabin_miller as is_prime
|
||||
|
||||
|
||||
def as_number(xs) -> int:
|
||||
return int("".join(map(str, xs)))
|
||||
|
||||
|
||||
def list_diff(xs, ys):
|
||||
xs = list(xs)
|
||||
for y in ys:
|
||||
xs.remove(y)
|
||||
return xs
|
||||
|
||||
|
||||
def combs(xs, size):
|
||||
return sorted([p
|
||||
for cs in combinations(xs, size)
|
||||
for p in permutations(cs)])
|
||||
|
||||
|
||||
def count(min_set_size: int, min_num: int, remaining: list[int]) -> int:
|
||||
if not remaining:
|
||||
return 1
|
||||
|
||||
result = 0
|
||||
# There are no pandigital primes with 9 digits, so we only check till 8.
|
||||
for set_size in range(min_set_size, 9):
|
||||
for subset in combs(remaining, set_size):
|
||||
n = as_number(subset)
|
||||
if n > min_num and is_prime(n):
|
||||
new_remaining = list_diff(remaining, subset)
|
||||
result += count(set_size, n, new_remaining)
|
||||
return result
|
||||
|
||||
|
||||
def euler_118():
|
||||
return count(1, 0, [1, 2, 3, 4, 5, 6, 7, 8, 9])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
solution = euler_118()
|
||||
print("e118.py: " + str(solution))
|
||||
assert(solution == 44680)
|
||||
|
|
@ -70,6 +70,9 @@ def is_prime_rabin_miller(number):
|
|||
""" Rabin-Miller Primality Test """
|
||||
witnesses = [2, 3, 5, 7, 11, 13, 17, 23, 29, 31, 37, 41, 43, 47, 53]
|
||||
|
||||
if number < 2:
|
||||
return False
|
||||
|
||||
if number in witnesses:
|
||||
return True
|
||||
|
||||
|
|
Loading…
Reference in New Issue