0

I want to use sympy to reproduce a result obtained with the Wolfram Language.

Using Wolframcloud, this expression

Solve[m^2+m*n==500 && m>n,{m,n},PositiveIntegers]

Gives the result I am looking for:

{{m->20,n->5}}

How can I reproduce this using sympy?

I have tried

import sympy as sp
m,n = sp.symbols('m n',integer=True)
sp.solve(m**2 + m*n - 500, m,n)

which gives

[(m, -m + 500/m)]

which is correct, but not particularly helpful.

Note, this question is inspired by Project Euler Problem 9.

Nigel Davies
  • 1,640
  • 1
  • 13
  • 26

1 Answers1

3

You should use diophantine for integer solutions:

In [10]: m, n = symbols('m, n')                                                                                                                

In [11]: sols = diophantine(m**2 + m*n - 500, (m, n))                                                                                          

In [12]: sols                                                                                                                                  
Out[12]: 
{(-500, 499), (-250, 248), (-125, 121), (-100, 95), (-50, 40), (-25, 5), (-20, -5), (-10, -40), (-5, -95), (-4, -121), (-2, -248), (-1, -499)
, (1, 499), (2, 248), (4, 121), (5, 95), (10, 40), (20, 5), (25, -5), (50, -40), (100, -95), (125, -121), (250, -248), (500, -499)}

That gives solutions for integer m, n. You can filter the solutions for the ones satisfying your conditions:

In [13]: {(m, n) for m, n in sols if m > n and m > 0 and n > 0}                                                                                
Out[13]: {(20, 5)}
Oscar Benjamin
  • 12,649
  • 1
  • 12
  • 14