Java Reference
In-Depth Information
function factorize(event) {
event.preventDefault(); // prevent the form from being
submitted
var number = Number(form.number.value);
var factors = String(factorsOf(number));
document.getElementById("output").innerHTML = factors;
}
function factorsOf(n) {
if (n < 0) {
throw new RangeError("Argument Error: Number must be
positive");
}
if (Math.floor(n) !== n) {
throw new RangeError("Argument Error: Number must be
an
integer");
}
var factors = [];
for (var i=1 , max = Math.sqrt(n); i <= max ; i++) {
if (n%i === 0){
factors.push(i,n/i);
}
}
return factors.sort(function(a,b) { return a > b; });
}
This uses the same factorsof() function from Chapter 9 and adds a submit event
listener to the form. When the form is submitted, it will find the factors of the number in
the input field and then place the result inside the output div.
 
Search WWH ::




Custom Search