0
$\begingroup$

How do I get Mathematica to stop a solver and give a result as soon as it finds the first solution instance?

I tried this:

Solve[x^2 + y^2 == z^2 && x > 5, {x, y, z}, Integers]
$\endgroup$
  • $\begingroup$ Surely, you meant Solve not Soln? $\endgroup$ – m_goldberg Jun 12 '15 at 17:08
  • $\begingroup$ @m_goldberg True! Thank you. How to stop the calculation after the first instance? Best $\endgroup$ – user30115 Jun 12 '15 at 17:12
  • 2
    $\begingroup$ Use FindInstance instead of Solve? $\endgroup$ – MikeLimaOscar Jun 12 '15 at 17:17
  • $\begingroup$ @MikeLimaOscar True! Thank you. More precisely does there exists a code to stop the computation after a precise number of instance? $\endgroup$ – user30115 Jun 12 '15 at 17:22
3
$\begingroup$
FindInstance[x^2 + y^2 == z^2 && x > 5, {x, y, z}, Integers, 1]
(* Results {{x -> 7, y -> 0, z -> 7}} *)

This tries to find 1 instance. If you want to look for two solutions:

 FindInstance[x^2 + y^2 == z^2 && x > 5, {x, y, z}, Integers, 2]
(* Results  {{x -> 15, y -> -20, z -> -25}, {x -> 919, y -> 0, z -> 919}} *)

However, look out because you may receive a warning for 3 or more on failing to find any additional integer solutions and being unable to prove that more do not exist.

FindInstance[x^2 + y^2 == z^2 && x > 5, {x, y, z}, Integers, 25]

 FindInstance::fwsol: Warning: FindInstance found only 2 instance(s), 
but it was not able to prove 3 instances do not exist. >>

If you want any more solutions, try using different RandomSeed (see docs) or alternatively this code (not the fastest) which generates many random solutions as {x,y} pairs from which you can easily get z:

Select[DeleteDuplicates[
  Flatten[PowersRepresentations[#, 2, 2] & /@ 
  RandomInteger[{2, 50000}, 5000], 1]], 
 IntegerQ@Sqrt[#[[1]]^2 + #[[2]]^2] && #[[1]] > 5 &]
| improve this answer | |
$\endgroup$
1
$\begingroup$

I really prefer Solve for tackling this problem. If Solve is suitably constrained, it will deliver a much more interesting sample of the solution space.

Solve[x^2 + y^2 == z^2 && 5 < x < 20 && 0 < y < 50 && 0 < z, {x, y, z}, Integers]
{{x -> 7, y -> 24, z -> 25}, {x -> 8, y -> 15, z -> 17}, 
 {x -> 9, y -> 12, z -> 15}, {x -> 9, y -> 40, z -> 41}, 
 {x -> 12, y -> 5, z -> 13}, {x -> 12, y -> 9, z -> 15}, 
 {x -> 12, y -> 35, z -> 37}, {x -> 15, y -> 8, z -> 17}, 
 {x -> 15, y -> 20, z -> 25}, {x -> 15, y -> 36, z -> 39}, 
 {x -> 6, y -> 8, z -> 10}, {x -> 8, y -> 6, z -> 10}, 
 {x -> 10, y -> 24, z -> 26}, {x -> 12, y -> 16, z -> 20}, 
 {x -> 14, y -> 48, z -> 50}, {x -> 16, y -> 12, z -> 20}, 
 {x -> 16, y -> 30, z -> 34}, {x -> 18, y -> 24, z -> 30}}
| improve this answer | |
$\endgroup$
  • $\begingroup$ Thank you ! Thank you ! Thank you ! $\endgroup$ – user30115 Jun 29 '15 at 20:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.