# Generating Pythagorean Triples

JavaScript allows you to make web pages interactive by manipulating user inputted data. This tutorial shows how to collect data from an input field and use it to generate Pythagorean triples. The result is then displayed to user.

### How to generate Pythagorean triples

Take two positive integers x, y with x > y. A Pythagorean triple is of the form x2 - y2, 2xy, x2 + y2.

### The HTML code

First we need generate the HTML elements required. We will need:

• Two input boxes
• An input button
• A paragraph to display the result and any instructions.
<input id="seed1" />
<input id="seed2" />
<input type="button" value="Generate Triple" onclick="generateTriple()" />

<p id="result">
Enter two seed numbers into the boxes above.
</p>

### The JavaScript

Here is the JavaScript function code which is ideally placed in the head section of your HTML document.

<script>
function generateTriple() {
var x = document.getElementById('seed1').value;
var y = document.getElementById('seed2').value;

x = Math.round(x);
y = Math.round(y);
if (x < 1 || y < 1 || x == y || isNaN(x) || isNaN(y)) {
document.getElementById('result').innerHTML = "Enter two distinct positive integers.";
return;
}
var a = Math.abs(x * x - y * y);
var b = 2 * x * y;
var c = x * x + y * y;
document.getElementById('result').innerHTML = a + ", " + b + ", " + c + " is a Pythagorean triple.";
}
</script>

### Use the code to generate Pythagorean triples

See the code in action below. Enter two different positive whole numbers as seeds and click 'Generate Triple'.

Enter two seed numbers into the boxes above.