Pythagorean Triple Generator

By Matt Dunlop
on May 28, 2005

Version: 1

Type: Full Script

Category: Math Functions

Description: Pythagorean triples are the lengths of the sides of a right angled triangle which are all integers.

Enter how many triples you want to find, and the script will display them for you.

Working (and formatted) version of script:
http://xodus.xionenet.com/triples.php

ðŸ™‚

```<form action='<?=\$_SERVER['PHP_SELF']?>' method='post'>
<table>
<tr>
</tr>
<tr>
<td colspan='2'>Generate first <input type='text' name='num' size='3' maxlength='3' value='<?php if (isset(\$_POST['num'])) { echo \$_POST['num']; } else { echo "100"; } ?>' onfocus="value=''" /> triples</td>
<td><input type='submit' name='submit' value='go' /></td>
</tr>
<tr>
<td width='75'><b>length a</b></td>
<td width='75'><b>length b</b></td>
<td width='75'><b>hypoteneuse</b></td>
</tr>

<?php

/////////////////////
// a^2 + b^2 = c^2 //
/////////////////////

if (isset(\$_POST['submit'])) {
\$max = \$_POST['num']; // How many triples to find?
} else {
\$max = 0; // No value = no triples >:D
}

\$i = 1; // Triple Counter
\$c = 1; // Hypoteneuse length
\$f = 1; // Variable for alternating

while (\$i <= \$max)  { // Generate only number of triples required
\$csq = \$c*\$c;
\$b = 1;
while (\$b < \$c) { // Generating length of a different side
\$bsq = \$b*\$b;
\$asq = \$csq - \$bsq;
\$a = sqrt(\$asq);

// Display every other triple, otherwise duplicates will occur...
if (\$f) {
\$f = FALSE;
} else {
\$f = 1;
}

// If result is an integer, it's a triple!
if(ereg("^[0-9]+\$", \$a) && \$f) { // Is the result an integer?  If yes, we have a triple...
echo "<tr><td>\$a</td><td>\$b</td><td>\$c</td></tr>n";
\$i++; // Increment triple counter
}
\$b++; // Increment length B
}
\$c++; // Raise the hypoteneuse to look for more triples...
}
?>
</table>
</form>```
ï»¿