Pythagorean triples: Difference between revisions

(→‎{{header|Wren}}: Updated to Wren 0.4.0.)
Line 2,583:
 
But note that J's memory footprint reached 6.7GB during the computation, so to compute larger values the computation would have to be broken up into reasonable sized blocks.
==Traversal of the Tree of Primitive Pythagorean Triples==
On my laptop this code takes 1.35 seconds for a perimeter of up to 1 million, though it takes 2 minutes for 10 million, so performance is between the previous code "brute force" and what is called "slightly smarter approach" It could probably be sped up slightly by not sorting the triples (there is no need with this problem.)
<lang J>
mp =: +/ . * "2 1
 
T =: 3 3 3$ 1 _2 2 2 _1 2 2 _2 3 1 2 2 2 1 2 2 2 3 _1 2 2 _2 1 2 _2 2 3
 
branch =: dyad define NB. Go down one branch of the tree, usage: <perimeter> branch <triple>
(x >: +/"1 next) # next =. T (/:~ @ mp) y
)
 
pythag =: monad define NB. pythagorean triples with max perimeter
t1 =. 0 3$ 0
if. y >: 12 do.
t0 =. 1 3$ 3 4 5
while. #t0 > 0 do.
t =. {. t0
t1 =. t1, t
t0 =. (}. t0), y branch t
end.
end.
/:~ t1
)
 
count =: monad define "0 NB. count triples with max perimeter
y, (#t), +/ <. y % +/"1 t =. pythag y
)
 
(9!:11) 7 NB. change output precision
 
echo 'Counts of primitive and total number of Pythagorean triples with perimeter ≤ 10^n.'
echo count 10 ^ >: i.6
exit ''
</lang>
{{Out}}
<pre>
Counts of primitive and total number of Pythagorean triples with perimeter ≤ 10^n.
10 0 0
100 7 17
1000 70 325
10000 703 4858
100000 7026 64741
1000000 70229 808950
</pre>
 
=={{header|Java}}==
357

edits