mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-04 07:29:47 +08:00

* chore: Switch to Node 20 + Vitest * chore: migrate to vitest mock functions * chore: code style (switch to prettier) * test: re-enable long-running test Seems the switch to Node 20 and Vitest has vastly improved the code's and / or the test's runtime! see #1193 * chore: code style * chore: fix failing tests * Updated Documentation in README.md * Update contribution guidelines to state usage of Prettier * fix: set prettier printWidth back to 80 * chore: apply updated code style automatically * fix: set prettier line endings to lf again * chore: apply updated code style automatically --------- Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
54 lines
1.3 KiB
JavaScript
54 lines
1.3 KiB
JavaScript
/*
|
|
author: PatOnTheBack
|
|
license: GPL-3.0 or later
|
|
|
|
Modified from:
|
|
https://github.com/TheAlgorithms/Python/blob/master/maths/findLcm.py
|
|
|
|
More about LCM:
|
|
https://en.wikipedia.org/wiki/Least_common_multiple
|
|
*/
|
|
|
|
'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
|
|
|
|
while (true) {
|
|
if (lcm % num1 === 0 && lcm % num2 === 0) return lcm
|
|
lcm += maxNum
|
|
}
|
|
}
|
|
|
|
// 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 }
|