Skip to main content

Archive

Show more

How to find LCM of two numbers in javascript

how-to-find-lcm-of-two-numbers-in-javascript


Question: How to find LCM of two numbers in javascript

Answer:

First: using 'Math.max()', 'Math.min()' and 'while loop'.

function findLCM(n1, n2){
  
  let maxNumber = Math.max(n1, n2);
  let minNumber = Math.min(n1, n2);
  
  let i = maxNumber;
  while(i % minNumber !== 0){
    i += maxNumber;
  }
  return i;
}

console.log(findLCM(12, 13));

Output:

156


Second: this is similar to the first method but we are using 'ternary operator' to find 'max' and 'min' number.

function findLCM(n1, n2){
 let min = (n1 > n2) ? n1 : n2;
  
 while (true) {
  if (min % n1 == 0 && min % n2 == 0) {
   console.log(min);
   break;
 }
 min++;
 }
}

findLCM(12, 13);

Output:

156


Third: In this method, we will use math 'LCM' And 'HCF' relation formula.

LCM = (n1 * n2) / HCF; // maths magic
function findLCM(n1, n2){

let hcf;
for (let i = 1; i <= n1 && i <= n2; i++) {
  if( n1 % i == 0 && n2 % i == 0) {
     hcf = i;
  }
}
  
let lcm = (n1 * n2) / hcf;
console.log(lcm);
}
  
findLCM(12, 13);

Output:

156


Four: Here you can see recursion plus GCD and 'ternary operator'(HCF And GCD both are the same). This concept is similar to third method.

function FindGCD(m1, m2) {
 return m2 == 0 ? m1 : FindGCD(m2, m1 % m2);
}

function findLCM(n1, n2) {
 return n1 * n2 / FindGCD(n1, n2);
}

console.log(findLCM(12, 13));

Output:

156


We try to provide you the best content, if there is any mistake in this article or there is any mistake in code, then let us know.

Comments