2019-07-01 14:35:50 -04:00
|
|
|
/*
|
|
|
|
|
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
|
2019-07-01 14:35:50 -04:00
|
|
|
|
|
|
|
|
More about LCM:
|
|
|
|
|
https://en.wikipedia.org/wiki/Least_common_multiple
|
|
|
|
|
*/
|
|
|
|
|
|
2020-05-03 09:05:12 +02:00
|
|
|
'use strict'
|
2019-08-05 15:34:17 -04:00
|
|
|
|
2022-10-24 07:54:45 -04:00
|
|
|
import { findHCF } from './FindHcf'
|
2022-10-23 03:19:19 -04:00
|
|
|
|
2019-07-01 14:35:50 -04:00
|
|
|
// Find the LCM of two numbers.
|
2020-10-11 19:47:49 +00:00
|
|
|
const findLcm = (num1, num2) => {
|
|
|
|
|
// If the input numbers are less than 1 return an error message.
|
|
|
|
|
if (num1 < 1 || num2 < 1) {
|
2022-10-23 03:19:19 -04:00
|
|
|
throw Error('Numbers must be positive.')
|
2020-10-11 19:47:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// If the input numbers are not integers return an error message.
|
|
|
|
|
if (num1 !== Math.round(num1) || num2 !== Math.round(num2)) {
|
2022-10-23 03:19:19 -04:00
|
|
|
throw Error('Numbers must be whole.')
|
2020-10-11 19:47:49 +00:00
|
|
|
}
|
|
|
|
|
|
2022-04-20 12:59:29 -03:00
|
|
|
// Get the larger number between the two
|
|
|
|
|
const maxNum = Math.max(num1, num2)
|
|
|
|
|
let lcm = maxNum
|
2019-07-01 14:35:50 -04:00
|
|
|
|
2020-05-03 09:05:12 +02:00
|
|
|
while (true) {
|
2022-04-20 12:59:29 -03:00
|
|
|
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
|
|
|
}
|
2019-07-01 14:35:50 -04:00
|
|
|
}
|
|
|
|
|
|
2022-10-23 03:19:19 -04: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.')
|
|
|
|
|
}
|
|
|
|
|
|
2023-10-03 23:08:19 +02:00
|
|
|
return (num1 * num2) / findHCF(num1, num2)
|
2022-10-23 03:19:19 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export { findLcm, findLcmWithHcf }
|