# Getting the first solution instance

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]

• Surely, you meant Solve not Soln? – m_goldberg Jun 12 '15 at 17:08
• @m_goldberg True! Thank you. How to stop the calculation after the first instance? Best – user30115 Jun 12 '15 at 17:12
• Use FindInstance instead of Solve? – MikeLimaOscar Jun 12 '15 at 17:17
• @MikeLimaOscar True! Thank you. More precisely does there exists a code to stop the computation after a precise number of instance? – user30115 Jun 12 '15 at 17:22

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[#[]^2 + #[]^2] && #[] > 5 &]


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}}

• Thank you ! Thank you ! Thank you ! – user30115 Jun 29 '15 at 20:35