So spoilers here; I am not very knowledgeable w/r/t maths, so had to look this up, but:
- lowest common multiple of
a
andb
(make it a function likelcm(a, b)
) is equal toa
timesb
divided by the greatest common divisor ofa
andb
. - So this looks like
(a * b) / gcd(a, b)
. - GCD is very easy to calculate:
(nb thefunction gcd(a, b) { while (b !== 0) { [a, b] = [b, a % b]; } return a; }
[a, b] = [b, a]
is an easy way to swap variables without using a temporary variable, I just used it to save space) - Now, if you have a range of numbers low…high, you can just run the
lcm
function on the first two, then take the result of that and run it on that and the next number and so on. In other words,reduce
.
function smallestCommons(arr) {
return inclusiveRange(Math.min(...arr), Math.max(...arr)).reduce(lcm);
}
function inclusiveRange(a, b) {
const range = [];
for (let i = a; i <= b; i++) {
range.push(i);
}
return range;
}
function gcd(a, b) {
while (b !== 0) {
[a, b] = [b, a % b];
}
return a;
}
function lcm(a, b) {
return (a * b) / gcd(a, b)
}
The performance will never be fantastic because the number of computations just explodes as you add more numbers to the range, but I think it should be pretty good - passes the tests no problem, and there’s no visible slowdown when I run the function in my browser.
Edit: