JavaScript code to find prime factors

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

Coding for Kids

What is coding? In coding we build a program to do a specific task for us. Code: A code is a set of computer instructions and when you will ...