Took 4 minutes and 48 seconds to code JavaScript prototype to find prime factors of a given number. Here is the code snippet.
Code (Run Code):
function checkPrime(num) {
if (num == 1) {
return false;
} else if (num == 2) {
return true;
}
for (var x = 2; x < num; x++) {
if (num % x == 0) {
return false;
}
}
return true;
}
function primeFactor(num) {
for (var i = 2; i < num; i++) {
if (num % i == 0) {
return i;
}
}
}
function primeFactors(num) {
arr = [];
x = num;
while (!checkPrime(x)) {
arr.push(primeFactor(x));
x = x / primeFactor(x);
}
arr.push(x);
return arr;
}
function main() {
document.getElementById('demo').innerHTML =
primeFactors(document.getElementById('num').value);
}
No comments:
Post a Comment