📝 docs(0031):添加动态规划数学原理和权威文献参考

 feat(0032):新增Pandigital数字问题解决方案
This commit is contained in:
2025-12-31 18:06:10 +08:00
parent 8ee312ac1d
commit ff1c6bffeb
3 changed files with 211 additions and 12 deletions

View File

@@ -0,0 +1,82 @@
"""
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()

View File

@@ -0,0 +1,7 @@
比较容易确定这样一点:
1. 可实现的数位分布【234】【144】。
2. 1位数 2-9
3. 2位数 12-98
4. 4位数 1234-9876
所以,最简单的就是试算所有可能。我也考虑了使用排列方法进行计算,但是效率比直接计算要略低。