SIGN IN SIGN UP

Algorithms and Data Structures implemented in JavaScript for beginners, following best practices.

34084 0 0 JavaScript
/*
author: PatOnTheBack
license: GPL-3.0 or later
Modified from:
2020-05-05 16:58:57 +05:30
https://github.com/TheAlgorithms/Python/blob/master/maths/findLcm.py
More about LCM:
https://en.wikipedia.org/wiki/Least_common_multiple
*/
2020-05-03 09:05:12 +02:00
'use strict'
import { findHCF } from './FindHcf'
// Find the LCM of two numbers.
const findLcm = (num1, num2) => {
// If the input numbers are less than 1 return an error message.
if (num1 < 1 || num2 < 1) {
throw Error('Numbers must be positive.')
}
// If the input numbers are not integers return an error message.
if (num1 !== Math.round(num1) || num2 !== Math.round(num2)) {
throw Error('Numbers must be whole.')
}
// Get the larger number between the two
const maxNum = Math.max(num1, num2)
let lcm = maxNum
2020-05-03 09:05:12 +02:00
while (true) {
if (lcm % num1 === 0 && lcm % num2 === 0) return lcm
2020-05-05 16:58:57 +05:30
lcm += maxNum
2020-05-03 09:05:12 +02:00
}
}
// Typically, but not always, more efficient
const findLcmWithHcf = (num1, num2) => {
// If the input numbers are less than 1 return an error message.
if (num1 < 1 || num2 < 1) {
throw Error('Numbers must be positive.')
}
// If the input numbers are not integers return an error message.
if (num1 !== Math.round(num1) || num2 !== Math.round(num2)) {
throw Error('Numbers must be whole.')
}
return (num1 * num2) / findHCF(num1, num2)
}
export { findLcm, findLcmWithHcf }