fork download
  1. from itertools import product, combinations_with_replacement
  2. import time
  3. import threading
  4.  
  5. # 配置参数(可根据需要修改)
  6. TARGET = 228774 # 目标值
  7. MIN_PRODUCT = 74000 # 单个乘积的最小值
  8. MAX_PRODUCT = 115000 # 单个乘积的最大值
  9. VALUES = [35,40.5,58,67,73,90.5] # 系数列表
  10. MAX_VARS = 3 # 最多使用的变量数
  11. SOLVER_TIMEOUT = 30 # 每个求解器的超时时间(秒)
  12.  
  13. def is_valid_product(p):
  14. """检查单个乘积是否在有效范围内"""
  15. return MIN_PRODUCT <= p <= MAX_PRODUCT
  16.  
  17. def find_single_variable_solutions():
  18. """查找单个数的解(a*x = TARGET)"""
  19. solutions = []
  20. for a in VALUES:
  21. x = TARGET / a
  22. if x.is_integer() and 1 <= x <= 10000 and is_valid_product(a * x):
  23. solutions.append((a, x))
  24. return solutions
  25.  
  26. def find_two_variable_solutions():
  27. """查找两个数的解(a*x + b*y = TARGET)"""
  28. solutions = []
  29. for a, b in product(VALUES, repeat=2):
  30. if a == b: # 避免重复组合
  31. continue
  32. max_x = int((TARGET - MIN_PRODUCT) / a)
  33. for x in range(1, max_x + 1):
  34. ax = a * x
  35. if not is_valid_product(ax):
  36. continue
  37. remainder = TARGET - ax
  38. if remainder < MIN_PRODUCT:
  39. continue
  40. y = remainder / b
  41. if y.is_integer() and 1 <= y <= 10000 and is_valid_product(b * y):
  42. solutions.append((a, x, b, y))
  43. return solutions
  44.  
  45. def find_three_variable_solutions():
  46. """查找三个数的解(a*x + b*y + c*z = TARGET)"""
  47. solutions = []
  48. for a, b, c in combinations_with_replacement(VALUES, 3):
  49. # 确保三个数不全相同,减少重复计算
  50. if len({a, b, c}) == 1:
  51. continue
  52.  
  53. max_x = int((TARGET - 2 * MIN_PRODUCT) / a)
  54. for x in range(1, max_x + 1):
  55. ax = a * x
  56. if not is_valid_product(ax):
  57. continue
  58. remainder1 = TARGET - ax
  59. if remainder1 < 2 * MIN_PRODUCT:
  60. continue
  61.  
  62. max_y = int((remainder1 - MIN_PRODUCT) / b)
  63. for y in range(1, max_y + 1):
  64. by = b * y
  65. if not is_valid_product(by):
  66. continue
  67. remainder2 = remainder1 - by
  68. if remainder2 < MIN_PRODUCT:
  69. continue
  70. z = remainder2 / c
  71. if z.is_integer() and 1 <= z <= 10000 and is_valid_product(c * z):
  72. solutions.append((a, x, b, y, c, z))
  73. return solutions
  74.  
  75. def find_balanced_solutions(solutions, var_count):
  76. """从所有解中筛选出最平衡的解"""
  77. if var_count == 1:
  78. return solutions # 单变量无需平衡筛选
  79.  
  80. # 计算解的平衡性(变量间差异最小)
  81. balanced = []
  82. for sol in solutions:
  83. vars = sol[1::2] # 提取x, y, z
  84. diff = max(vars) - min(vars)
  85. balanced.append((diff, sol))
  86.  
  87. # 按差异排序,取前5个
  88. return [s for _, s in sorted(balanced, key=lambda x: x[0])[:5]]
  89.  
  90. def run_with_timeout(func, args=(), kwargs=None, timeout=SOLVER_TIMEOUT):
  91. """运行函数并设置超时限制"""
  92. if kwargs is None:
  93. kwargs = {}
  94.  
  95. result = []
  96. error = []
  97.  
  98. def wrapper():
  99. try:
  100. result.append(func(*args, **kwargs))
  101. except Exception as e:
  102. error.append(e)
  103.  
  104. thread = threading.Thread(target=wrapper)
  105. thread.daemon = True
  106. thread.start()
  107. thread.join(timeout)
  108.  
  109. if thread.is_alive():
  110. print(f"警告: {func.__name__} 超时({timeout}秒),跳过此方法")
  111. return None
  112.  
  113. if error:
  114. raise error[0]
  115.  
  116. return result[0]
  117.  
  118. def display_solutions():
  119. """显示所有找到的解"""
  120. print(f"寻找 {TARGET} 的解(单个乘积范围: {MIN_PRODUCT}~{MAX_PRODUCT},超时时间: {SOLVER_TIMEOUT}秒)")
  121.  
  122. # 优先查找单变量解
  123. print("\n尝试单变量解...")
  124. single_solutions = run_with_timeout(find_single_variable_solutions)
  125. if single_solutions:
  126. print("\n找到单变量解:")
  127. for a, x in single_solutions:
  128. print(f"a={a}, x={x}, a*x={a*x}")
  129. return
  130.  
  131. # 其次查找双变量解
  132. print("\n尝试双变量解...")
  133. two_solutions = run_with_timeout(find_two_variable_solutions)
  134. if two_solutions:
  135. print("\n找到双变量解:")
  136. balanced = find_balanced_solutions(two_solutions, 2)
  137. for a, x, b, y in balanced:
  138. print(f"a={a}, x={x}, b={b}, y={y}, a*x={a*x}, b*y={b*y}, 总和={a*x + b*y}")
  139. return
  140.  
  141. # 最后查找三变量解(仅当TARGET > 200000时)
  142. if TARGET > 200000:
  143. print("\n尝试三变量解...")
  144. three_solutions = run_with_timeout(find_three_variable_solutions)
  145. if three_solutions:
  146. print("\n找到三变量解:")
  147. balanced = find_balanced_solutions(three_solutions, 3)
  148. for a, x, b, y, c, z in balanced:
  149. print(f"a={a}, x={x}, b={b}, y={y}, c={c}, z={z}, "
  150. f"a*x={a*x}, b*y={b*y}, c*z={c*z}, 总和={a*x + b*y + c*z}")
  151. return
  152.  
  153. print("\n没有找到符合条件的解,或所有方法超时。")
  154.  
  155. if __name__ == "__main__":
  156. start_time = time.time()
  157. display_solutions()
  158. print(f"\n总耗时: {time.time() - start_time:.2f}秒")
Success #stdin #stdout 0.06s 10368KB
stdin
Standard input is empty
stdout
寻找 228774 的解(单个乘积范围: 74000~115000,超时时间: 30秒)

尝试单变量解...

尝试双变量解...

找到双变量解:
a=35, x=3264, b=40.5, y=2828.0, a*x=114240, b*y=114534.0, 总和=228774.0
a=40.5, x=2828, b=35, y=3264.0, a*x=114534.0, b*y=114240.0, 总和=228774.0
a=35, x=3266, b=73, y=1568.0, a*x=114310, b*y=114464.0, 总和=228774.0
a=73, x=1568, b=35, y=3266.0, a*x=114464, b*y=114310.0, 总和=228774.0

总耗时: 0.02秒