Files
Sidney Zhang ff1c6bffeb 📝 docs(0031):添加动态规划数学原理和权威文献参考
 feat(0032):新增Pandigital数字问题解决方案
2025-12-31 18:06:10 +08:00

83 lines
2.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
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, the 5-digit number, 15234, is 1 through 5 pandigital.
The product 7254 is unusual, as the identity, 39 × 186 = 7254,
containing multiplicand, multiplier, and product is 1 through 9 pandigital.
Find the sum of all products whose multiplicand/multiplier/product identity can be written
as a 1 through 9 pandigital.
HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.
"""
import time
from itertools import permutations
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start:.6f} seconds")
return result
return wrapper
def is_pandigital(n: list[str]) -> bool:
if n[0] == "1":
x = [int("".join(n[:2]))]
y = [int("".join(n[2:5]))]
else:
x = [int(n[0]), int("".join(n[:2]))]
y = [int("".join(n[1:5])), int("".join(n[2:5]))]
z = int("".join(n[5:]))
for i in range(len(x)):
if x[i] * y[i] == z:
return True
return False
def pandigital_products() -> list[int]:
all_permuts = permutations("123456789")
res = set()
for perm in all_permuts:
if is_pandigital(list(perm)):
res.add(int("".join(perm[5:])))
return list(res)
@timer
def main_compute() -> None:
res = set()
for x in range(2, 10):
for z in range(1234, 9877):
if z % x == 0:
y = z // x
if "".join(sorted(str(x) + str(y) + str(z))) == "123456789":
res.add(z)
print(f"{x} * {y} = {z}")
for x in range(12, 99):
for z in range(1234, 9877):
if z % x == 0:
y = z // x
if "".join(sorted(str(x) + str(y) + str(z))) == "123456789":
res.add(z)
print(f"{x} * {y} = {z}")
res = list(res)
print(f"= {sum(res)}")
@timer
def main() -> None:
res = pandigital_products()
print("+".join(map(str, res)))
print(f"= {sum(res)}")
if __name__ == "__main__":
main()
main_compute()