如何构造n阶平方幻方?求高效通用实现方案
求通用n阶平方幻方高效构造方案
- 目标:构造元素为不同自然数平方的幻方,当前针对和为8515的4阶场景,已找到200组满足行/列和要求的4元平方组合,但无法将这些组合拼接成包含16个不同元素的完整幻方(8515是4阶平方幻方的候选和值)。
- 核心需求:开发可适配任意目标和值、任意n阶的通用构造程序。
- 过往尝试:暴力搜索、多种启发式搜索算法、图论建模、二次函数优化思路,均未取得理想效果。
更新:当前思路代码
目前尝试通过统计候选组合中元素的出现频率,对组合进行排序以优化后续匹配效率,但仍不清楚如何完成最终的幻方拼接逻辑,以下是当前实现代码:
import math import time from collections import Counter def find_solutions(N): solutions = set() sqrt_N = int(math.isqrt(N)) # 计算N的平方根 for a in range(sqrt_N + 1): a_squared = a**2 for b in range(sqrt_N + 1): # 从0开始遍历 b_squared = b**2 for c in range(sqrt_N + 1): # 从0开始遍历 c_squared = c**2 remaining = N - a_squared - b_squared - c_squared if remaining < 0: break # 剩余值为负时终止当前循环 d = int(math.isqrt(remaining)) d_squared = d**2 if a_squared + b_squared + c_squared + d_squared == N and len({a, b, c, d}) == 4: solutions.add(tuple(sorted([a, b, c, d]))) return solutions # 指定目标和值N N = 8515 # 可修改为自定义目标值 solutions = find_solutions(N) solution_count = len(solutions) if solution_count == 0: print(f"未找到满足a² + b² + c² + d² = {N}的解") else: print(f"满足a² + b² + c² + d² = {N}的唯一解数量:{solution_count}") # 统计所有解中每个数字的出现次数 total_counts = Counter([num for sublist in solutions for num in sublist]) # 计算每个数字的出现占比 total_solutions = sum(total_counts.values()) number_percentages = {num: (count / total_solutions) * 100 for num, count in total_counts.items()} # 按组合中元素的总出现占比降序排序解 sorted_solutions = sorted(solutions, key=lambda solution: sum(number_percentages[num] for num in solution), reverse=True) # 输出排序结果 print("\n按总出现占比降序排列的解:") print("{:<30} {:<10}".format("[a, b, c, d]", "总占比")) for solution in sorted_solutions: total_percentage = sum(number_percentages[num] for num in solution) print("{:<30} {:<10.5f}%".format(str(solution), total_percentage))
内容的提问来源于stack exchange,提问作者Ansar
相关产品推荐
相关产品推荐

