如果某个值等于 yx^2,如何在 Python 中求出 x 和 y 的整数值?

0 投票
1 回答
57 浏览
提问于 2025-04-14 17:16
import sympy

def find_integer_values(value):
  x, y = sympy.symbols('x y', integer=True)
  equation = sympy.Eq(y * x**2, value)         

  # Solve for integer values of x and y
  solutions = sympy.solve(equation, (x, y), dict=True)

  # Filter solutions to include only integers
  integer_solutions = [(sol[x], sol[y]) for sol in solutions if sympy.simplify(sol[x]).is_integer and sympy.simplify(sol[y]).is_integer]
 
  return integer_solutions

# Example usage:
given_value = 1920

integer_solutions = find_integer_values(given_value)

if integer_solutions:
  print("Integer solutions for x and y:", integer_solutions)
else:
  print("No integer solutions found.")

这段代码的目的是找出 x 和 y 的值,而这两个值都应该是整数。但是这部分代码有点问题-

integer_solutions = [(sol[x], sol[y]) for sol in solutions if sympy.simplify(sol[x]).is_integer and sympy.simplify(sol[y]).is_integer]

如果你能给我一些建议,告诉我怎么修复这个问题,我会非常感激。

1 个回答

1

看起来你想把一个数字分成平方部分和非平方部分。这其实就是在对这个数字进行因式分解:

def mysolve(value):
    from sympy.solvers.diophantine.diophantine import square_factor
    # return values for x*y**2 = value
    from sympy.abc import x, y
    s = square_factor(value)
    return {x: value//s**2, y:s}

>>> mysolve(1920)
{x: 30, y: 8}
>>> 30*8**2
1920

如果 s 是 1,你可以抛出一个错误。

撰写回答