JavaScript prototype to calculate HCF of two numbers

HCF is Highest Common Factor. For example :- HCF of 4 and 6 is 2.
Prime Factors of 4 = 2, 2 
Prime Factors of 6 = 2, 3 
So 2 is common in both, hence the HCF of 4 and 6 is 2.

Took  32 minutes and 25 seconds to code JavaScript prototype to calculate HCF 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 calculateHCF(num1, num2) {
arr1 = primeFactors(num1);
arr2 = primeFactors(num2);
arr3 = [];
for (var i = 0; i < arr1.length; i++) {
for (var j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
arr3.push(arr1[i]);
delete arr1[i];
delete arr2[j];
}
}
}
product = arr3[0];
for (var y = 1; y < arr3.length; y++) {
product *= arr3[y];
}
if (product == undefined) {
return 1;
} else {
return product;
}
}

function main(){
document.getElementById("result").innerHTML =
calculateHCF(document.getElementById("num1").value, document.getElementById("num2").value);
}

No comments:

Post a Comment

GITEX Dubai Talk by Saion Gupta and Saiasmi Gupta

Good morning, everyone. I'm Saion Gupta, the Founder of 10xCoderKids and the Guinness World Record holder for the youngest computer prog...