|
GCD Calculation:
|
The html looks like this
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function calculate() {
var xStr = document.getElementById("numX").value;
var yStr = document.getElementById("numY").value;
var output;
if (xStr == "" || yStr == "")
output = "";
else if (!isInteger(xStr) || !isInteger(yStr))
output = "Not an integer";
else {
var x = parseInt(xStr, 10);
var y = parseInt(yStr, 10);
if (x < 0 || x >= 9007199254740992 || y < 0 || y >= 9007199254740992)
output = "Number out of range";
else
output = gcd(Math.abs(x), Math.abs(y)).toString(10);
}
document.getElementById("output").value = output;
}
// Returns the GCD of the given integers. Each input must be non-negative.
function gcd(x, y) {
while (y != 0) {
var z = x % y;
x = y;
y = z;
}
return x;
}
// Tests whether the given string represents an integer.
function isInteger(str) {
return /^-?\d+$/.test(str);
}
</SCRIPT>
</HEAD>
<BODY >
<P></TABLE>
<TABLE border=1 cellPadding=1 cellSpacing=0 ALIGN=CENTER width=750>
<TR><TD valign=top width=350>
<PRE>
<b>GCD Calculation:</b>
<form action="#" method="get" onsubmit="calculate(); return false">
<table class="noborder">
<tbody>
<tr>
<td><label for="numX"><var>x</var>:</label></td>
<td><input type="number" id="numX" style="width:12em" oninput="calculate()"/></td>
</tr>
<tr>
<td><label for="numY"><var>y</var>:</label></td>
<td><input type="number" id="numY" style="width:12em" oninput="calculate()"/></td>
</tr>
<tr>
<td><label for="output">gcd(<var>x</var>, <var>y</var>):</label></td>
<td><input type="text" id="output" readonly="readonly" style="width:12em"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Calculate"/></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
|