Skip to content

Instantly share code, notes, and snippets.

@zzh1996
Last active May 12, 2021 09:03
Show Gist options
  • Save zzh1996/9686fdda15b69e4241cf8e4933cf653a to your computer and use it in GitHub Desktop.
Save zzh1996/9686fdda15b69e4241cf8e4933cf653a to your computer and use it in GitHub Desktop.
solve_mod_mathematica
from wolframclient.evaluation import WolframLanguageSession
from wolframclient.language import wl
def solve_mma(eqn, modulus):
if eqn.number_of_arguments() != 1:
raise NotImplementedError('Not univariate')
if eqn.is_polynomial(eqn.args()[0]):
poly = eqn
elif eqn.is_relational() and eqn.operator() is operator.eq:
poly = eqn.lhs() - eqn.rhs()
else:
raise NotImplementedError('Not polynomial or equation')
p = int(0)
for c, e in poly.coefficients():
p = wl.Plus(p, wl.Times(int(c), wl.Power(wl.x, int(e))))
session = WolframLanguageSession()
r = session.evaluate(wl.Quiet(wl.Solve(wl.Equal(p, int(0)), wl.x, Modulus=int(modulus))))
ans = []
for i in r:
ans.append(session.evaluate(wl.Quiet(wl.ReplaceAll(*i)(wl.x))))
session.terminate()
return ans
# Usage:
# var('x')
# solve_mma(x ^ 2 == 1, 15)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment