function findDivisors(n, includeSelf){
includeSelf = includeSelf || false;
if (n == 1) {
return [];
}
var maxDiv = Math.ceil(Math.sqrt(n));
var divisors = [];
for (var p = 2; p <= maxDiv; p++) {
if (n % p == 0) {
q = n / p;
divisors.push(p);
divisors = divisors.concat(findDivisors(q, true));
if (divisors.reduce(function(a, b) { return a*b }) == n) {
return divisors;
}
}
}
if (includeSelf) {
divisors.push(n);
}
return divisors;
}
$(document).ready(function(){
$(".btn-test").click(function(){
var num = parseInt($("#num").val(), 10);
var box = $("#result");
if (isNaN(num)) {
box.html("Invalid number");
} else if (num < 1) {
box.html("Only positive number can be checked!");
} else {
box.html("Checking in progress...");
var result = findDivisors(num, false);
if (result.length > 0) {
box.html(num + " <strong>is NOT prime</strong>! Prime divisors: <strong>" + result.join(" x ") + " = " + num + "</strong>");
} else {
box.html(num + " <strong>is prime</strong>! No divisors except 1 and " + num);
}
}
box.trigger("autoresize");
});
});