Pythagorean Triplets

Python, 42

i=4
while i<203:print 2*i,i*i-1,i*i+1;i+=2

Javascript, 44 characters

Update:

for(i=s=0;i^400;)s+=[i+=4,r=i*i/4-1,r+2]+' '

I should have looked up an algorithm first. Well, can't beat python anyway.

Run in a console to see the result.

Old, slow, brute-force variant (140 characters)

for(q=a=[];563>++a;)for(b=a;--b;)(k=Math.sqrt(a*a+b*b))==~~k==function c(e,d,f){return f?c(c(f,e),d):d?c(d,e%d):e}(a,b,k)&&q.push([b,a,k]);q

J, 64 60 38 49 characters

100$}.~.(/:~*(0<*/*1=+./))"1[4$.$.(=/+/~)2^~i.699

Should've realised that such a big gain was probably flawed. Still uses the brute-force method, but done a bit more efficiently.

Explanation:

x=.2^~i.699 generates a list of ints from 0 to 699 and squares 2^~ them (~ here reverses the order of the arguments).

(=+/~) is a hook that generates an addition table and compares the result to the list. This gives me a three dimensional array with items which are either 1 or 0. A 1 means that a2+b2=c2.

$. converts to a sparse array. For my smaller (9) example I get:

   $.(=/+/~)2^~i.9
0 0 0 | 1
1 0 1 | 1
1 1 0 | 1
2 0 2 | 1
2 2 0 | 1
3 0 3 | 1
3 3 0 | 1
4 0 4 | 1
4 4 0 | 1
5 0 5 | 1
5 3 4 | 1
5 4 3 | 1
5 5 0 | 1
6 0 6 | 1
6 6 0 | 1
7 0 7 | 1
7 7 0 | 1
8 0 8 | 1
8 8 0 | 1

4$. just gives me the left part of this list.

(/:~*(0<*/*1=+./))"1[ decides which rows meet the criteria. (verb)"1 tells the verb to act on the individual rows rather than on the list. [ just separates the 1 and 4, otherwise J will think that 1 4 is a list of 2 numbers. '1=+./' gets the GCD of the three numbers and checks if it's 1. */ multiplies each triple together (getting 0 if it contains a 0) and these two are multiplied together. 0< turns the result into a boolean. * multiplies this result by each triple which eliminates all triples which contain a 0 or have a GCD which is not 1. /:~ sorts each triple.

~. selects the unique items from the list.

}. removes the first item (0 0 0) from the list.

100$ takes the first 100 items from the list.

The above is my answer to this question, but as a matter of interest I implemented grc's method, (27 characters):

2(*,.<:@^~,.>:@^~)2*2+i.100

Tags:

Math

Code Golf