JavaScript prototype to calculate LCM of two numbers

LCM is Lowest Common Multiple. For example :- LCM of 4 and 6 is 12.
Prime Factors of 4 = 2, 2
Prime Factors of 6 = 2, 3
So the LCM of 4 and 6 is 2 x 2 x 3 = 12.

Took 15 minutes and 21 seconds to code JavaScript prototype to calculate LCM of two numbers. 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 calculateLCM(num1, num2) {
arr1 = primeFactors(num1);
arr2 = primeFactors(num2);
arr3 = [];
for (var i = 0; i < arr1.length; i++) {
arr3.push(arr1[i])
for (var j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
delete arr2[j];
break;
}
}
}
for (var i = 0; i < arr2.length; i++) {
if (arr2[i] != undefined) {
arr3.push(arr2[i]);
}
}
product = arr3[0];
for (var y = 1; y < arr3.length; y++) {
product *= arr3[y];
}
return product;
}

function main(){
document.getElementById("result").innerHTML =
calculateLCM(document.getElementById("num1").value, document.getElementById("num2").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 ...