Skip to content
RSS feed tkhwang on GitHub tkhwang on Twitter

GCD (Greatest Common Divisor) and LCM (Least Common Multiple) in javascript

πŸ”₯ GCD (Greatest Common Divisor) : [object Object]

  • The GCD of num1 and num2 is the GCD of num2 and num1 % num2.
const getGCD = (num1, num2) => (num2 > 0 ? getGCD(num2, num1 % num2) : num1);
const getGCD = (num1, num2) => {
  while (num2 > 0) {
    let r = num1 % num2;
    num1 = num2;
    num2 = r;
  }

  return num1;
};

πŸ”₯ LCM (Least Common Multiple)

  • First divide by gcd to prevent the overflow of the product of two numbers.
const getLCM = (num1, num2) => (num1 / getGCD(num1, num2)) * num2;

πŸ“š References