Javascript code to find HCF and LCM of two numbers

Javascript code to find HCF and LCM of two numbers


1.First Method

function hl(){

let hcf;
// take input
const number1 = prompt('Enter a first positive integer: ');
const number2 = prompt('Enter a second positive integer: ');

// looping from 1 to number1 and number2
for (let i = 1; i <= number1 && i <= number2; i++) {

    // check if is factor of both integers
    if( number1 % i == 0 && number2 % i == 0) {
        hcf = i;
    }
}


// display the hcf 
console.log(`HCF of ${number1} and ${number2} is ${hcf}.`);
}

hl()

2.Second Method

function findHCF(x, y) {

 // If the input numbers are less than 1 return an error message.
 if (x < 1 || y < 1) {
    return "Please enter values greater than zero.";
 }

 // If the input numbers are not integers return an error message.
 if (x != Math.round(x) || y != Math.round(y)) {
    return "Please enter whole numbers.";
 }

 // Now apply Euclid's algorithm to the two numbers.
 while (Math.max(x, y) % Math.min(x, y) != 0) {
    if (x > y) {
       x %= y;
    }
    else {
       y %= x;
    }
 }
 
 // When the while loop finishes the minimum of x and y is the HCF.
 return Math.min(x, y);
}
findHCF(5,6) //output is 1

Post a Comment

0 Comments