Jump to content

Pythagorean triples: Difference between revisions

J: the easy implementation
m (→‎{{header|Java}}: Added optimizations inspired by C, hey cool my IDE at home converted tabs to spaces for me)
(J: the easy implementation)
Line 60:
return 0;
}</lang>output:<lang>Up to 100, there are 17 triples, of which 7 are primitive</lang>
 
=={{header|J}}==
 
Brute force approach:
 
<lang j>pytr=:3 :0
r=.i.0 3
for_a.1+i.<.(y-1)%3 do.
b=.1+a+i.<.(y%2)-3*a%2
c=. a +&.*: b
keep=. (c=<.c)*.y>:a+b+c
if.1 e.keep do.
r=.r, a,.b ,.&(keep&#) c
end.
end.
(,.~ prim"1)r
)
 
prim=:1 = 2 +./@{. |:</lang>
 
Example use:
 
First column indicates whether the triple is primitive, and the remaining three columns are a, b and c.
 
<lang j> pytr 100
1 3 4 5
1 5 12 13
0 6 8 10
1 7 24 25
1 8 15 17
0 9 12 15
1 9 40 41
0 10 24 26
0 12 16 20
1 12 35 37
0 15 20 25
0 15 36 39
0 16 30 34
0 18 24 30
1 20 21 29
0 21 28 35
0 24 32 40
(# , [: {. +/) pytr 10
0 0
(# , [: {. +/) pytr 100
17 7
(# , [: {. +/) pytr 1000
325 70
(# , [: {. +/) pytr 10000
4858 703</lang>
 
pytr 10000 takes 4 seconds on this laptop, and time to complete grows with square of perimeter, so pytr 1e6 should take a something like 11 hours using this algorithm on this machine.
 
=={{header|Java}}==
6,962

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.