The below formula can be used to get the LCM of two numbers. See Reduction by the greatest common divisor section in Wikipedia
a * b
lcm(a, b) = ―――――――――――
gcd(a, b)
GCD can be calculated by using the Euclidean AlgorithmSee Using Euclid's algorithm section in Wikipedia.
gcd(a, b) = gcd(b, a % b)
Using these two formulas, the LCM can be calculated as follow
console.time('new');
function gcd(a, b) {
while (b !== 0) {
var temp = a;
a = b;
b = temp % b;
// Can be written in ES6 as
// [a, b] = [b, a % b];
}
return a;
}
function lcm(a, b) {
return a * b / gcd(a, b);
}
var range = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
console.log(range.reduce(lcm, 1));
console.timeEnd('new');
This is very efficient than using while
and for
, see this JsFiddle demo.