Group Abstract Group Abstract

Message Boards Message Boards

Speeding code of plotting solutions to x^2+y^2= z^2 for integer x,y,z

"Can the code be improved?". The first step takes a long time.

First find the values of z = Sqrt[x^2 + y^2] for x and y integers between 1 and 10,000

t = Flatten[Table[{{x, y}, Sqrt[x^2 + y^2]}, {x, 10^4}, {y, 10^4}], 
   1];

Next find the points with z an integer

In[2]:= Length[s = Select[t, IntegerQ[#[[2]]] &]]

Out[2]= 28948

ListPlot {x,y}. Many of the points are multiples of small value solutions.

enter image description here

Now select the points where x and y have no common factors

In[4]:= Length[ss = Select[s[[All, 1]], GCD[Sequence @@ #] == 1 &]]

Out[4]= 3576

Plot those points

enter image description here

POSTED BY: Frank Kampas
7 Replies

I found this code on SE gives you instantaneous results (around half second to evaluate the entire notebook including plot and no compilation needed):

POSTED BY: Shenghui Yang
POSTED BY: Shenghui Yang
POSTED BY: Neil Singer

Thank you everybody for your help.

POSTED BY: Frank Kampas
Posted 4 years ago

Take a look at this, the function primpyths1, generates all primitive Pythagorean triangles with a given input value for x. The remainder of the code creates a table up to 10000, also creates a reversed copy and joins them and finally prints them out. On my pc it takes 1.88 seconds to complete.

The function can easily be altered to generate all Pythagorean triangles, just remove the GCD[x,#]==1 section and change the #<=x to #>x. and if you wish add , Sqrt[x^2 + m[[i]]^2] in the table section.

primpyths1[x_Integer] := (t = Select[Divisors[x^2], # <= x &];
  m = Sort[
    Select[(x^2 - t^2)/(2 t), 
     IntegerQ[#] && # <= x && GCD[x, #] == 1 &]];
  Table[{x, m[[i]]}, {i, 1, Length[m]}])


primp = Flatten[Table[primpyths1[i], {i, 3, 10000}], 1]; prmp1 = 
 RotateLeft /@ primp[[All, 1 ;; 2]]; allp = 
 Riffle[primp, prmp1]; ListPlot[allp, AspectRatio -> 1, 
 GridLines -> {{10000}, {10000}}]
POSTED BY: Paul Cleary
Posted 4 years ago

Related thread.

POSTED BY: Rohit Namjoshi

Thank you. I must admit I don't understand how genPTunder works.

POSTED BY: Frank Kampas
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard