One thing you can try is use the map() method to loop thru all the elements of your array.
What helped me was first visualize what the array with all the sequential sorted numbers looks like.
I built a function to do that.
Then I built a function to compute the lcm of 2 numbers.
Finally I mapped all the elements of the array to find the overall lcm among all these numbers, not just 2 of them.
For ex. [1, 5] will become [1, 2, 3, 4, 5] once all the sequential numbers are displayed and sorted.
Now I find the lcm between the first two numbers, 1 and 2, which is 2.
At this point I proceed to find the lcm of the array where the first element has become 2, so:
[2, 3, 4, 5]
Now I find the lcm between 2 and 3 which is 6. My array now becomes [6, 4, 5].
lcm of 6 and 4 is 12. So my array has reduced to [12, 5] and lcm between 12 and 5 is 60
My code is probably more complicated than in needs to be but if helps you here it is:
function smallestCommons(arr) {
//Sort the array in ascending order
arr.sort(function(a, b)
{
return a -b;
});
// Make a function to build an array where to store all the sequential numbers
function printAllSequentialNum(min, max)
{
var allSequentialNum = [];
for(var i = min; i <=max; i++)
{
allSequentialNum.push(i);
}
return allSequentialNum;
}
/* One way to solve this problem is by using the Euclid algorithm: LCM = n1 * n2 / GCD
Find the GCD first.*/
function lcm(num1, num2)
{
for(var GCD = num1; GCD>0; GCD–)
if(num2 % GCD === 0 && num1 % GCD === 0)
return (num1 * num2) / GCD;//This is the LCM of 2 numbers
}
//map the whole array to find the lcm not just between 2 numbers but among all of them
var multiple = arr[0];
printAllSequentialNum(arr[0], arr[1]).map((num, i) =>
{
multiple = lcm(multiple, num);
console.log(multiple);
});
return multiple;
}
smallestCommons([1,5]);