pythagorean triples
Pete_I
created: 2006-04-23 16:01:12
#!/usr/bin/perl
#generate pythagorean triples until n = ARGV[1]
#based on this: http://www.math.uic.edu/~fields/puzzle/triples.html
#a, b, c = n^2 - m^2, 2*m*n, n^2 + m^2
my($m, $n, $end);
$end  = $ARGV[0] || 5;
for($n = 1; $n <= $end; $n++) {
 for($m = 1; $m < $n; $m++) {
  printf("%d,%d,%d\n", ($n * $n - $m * $m), (2 * $m * $n), ($n * $n + $m * $m));
 }
}
Re: pythagorean triples
created: 2006-04-23 23:16:33
But that doesn't really give "all" of them - e.g. 9,12,15 isn't of that form, is it? (Of course it is a multiple of 3,4,5 which is of that form...)
Re^2: pythagorean triples
created: 2006-04-23 23:50:42
That's correct, but any integer multiple of a primitive Pythagorean triple is also a Pythagorean triple. (The proof is left as an exercise for the reader) This sequence generates the set of primitive Pythagorean triples (assuming that $m & $n are coprime)

thor

The only easy day was yesterday

Re^3: pythagorean triples
created: 2006-04-24 00:36:33
Well, it's true that the primitive triples are of that form, but not conversely; 6,8,10 occurs for n=3,m=1 (which are coprime), and that triple isn't primitive. So the code generates primitive (i.e. having no common factor) triples, but some others as well. The real point is that it isn't so easy to print a list of all Pythagorean triples without duplication, and I guess that thought was what motivated my reply.
Re^2: pythagorean triples
created: 2006-04-24 17:21:03

True, but it's fairly easy to filter out the non-primitives.

If m and n are both even, skip (a, b, and c will all be divisible by two).

If m and n are both odd, skip (a, b, and c will all be divisible by two).

If m and n have a divisor in common (e.g., GCD{12,3} != 1) skip (a, b, and c will have that factor in common).

The first case can be wrapped up in third case (actually, it can be wrapped up in the second case too), but I find that it makes things clearer to separate them out.

Re^3: pythagorean triples
created: 2006-04-25 00:23:43

The third case should of course have been written as:

If m and n have a divisor in common (e.g., GCD{m,n} != 1) skip (a, b, and c will have that divisor in common).

Sorry about that

Re: pythagorean triples
created: 2006-04-23 23:37:08
Any perlmonks who happen to be members of what Wikipedia refers to as "the mysterious religious and scientific society called Pythagoreans" might like this;)
Maybe it's useful for forecasting the future:)..The Wikipedia page Pythagoras states that "Pythagoras and his students believed that everything was related to mathematics and thought that everything could be predicted and measured in rhythmic patterns or cycles."

perlmonks.org content © perlmonks.org and chas, jgamble, Pete_I, Scott7477, thor

prlmnks.org © 2006 edmund von der burg (eccles & toad)

v 0.03