JavaScript Find LCM Example

In this example, you will learn to write a JavaScript program that finds the LCM of two numbers.
Check out all 100 + JavaScript Examples
Check out all JavaScript programs at All JavaScript Programs 

JavaScript Find LCM Example

// Find the LCM of two numbers.
function findLcm (num1, num2) {
  var maxNum
  var lcm
  // Check to see whether num1 or num2 is larger.
  if (num1 > num2) {
    maxNum = num1
  } else {
    maxNum = num2
  }
  lcm = maxNum

  while (true) {
    if ((lcm % num1 === 0) && (lcm % num2 === 0)) {
      break
    }
    lcm += maxNum
  }
  return lcm
}

// Run `findLcm` Function
var num1 = 12
var num2 = 76
console.log('LCM of ' + num1 + ' and ' + num2 + ' is ' + findLcm(num1, num2));

Output

LCM of 12 and 76 is 228
Check out all 100 + JavaScript Examples
Check out all JavaScript programs at All JavaScript Programs 

Comments