Continuing the discussion from freeCodeCamp Challenge Guide: Smallest Common Multiple:
I came to this solution doing the exercise, and even though it works, the console warns me of potential infinite loops and for large numbers I believe it is not very efficient because of the nested loop.
Could you correct this code or tell me how could I improve it?
After watching many guides I don’t get a hang of the reduce function.
function smallestCommons(arr) {
// Set smallest as start
let [starter, last] = arr.sort((a,b) => a - b);
let current = 1;
for (let i = starter; i <= last; i++) {
for (let j = 1; j != 0; j++) {
// evaluate multiples of Starter vs Current
if ((i * j) % current === 0) {
// When found evaluate next number in Range
current = i * j;
break;
}
}
}
return current;
}
console.log(smallestCommons([2,10])); // Result 2520
console.log(smallestCommons([23,18])); // Result 6056820
PS: “current” variable can be completely replaced by starter, I just changed it for readability.
function smallestCommons(arr) {
// Set smallest as start
let [starter, last] = arr.sort((a,b) => a - b);
for (let i = starter; i <= last; i++) {
for (let j = 1; j != 0; j++) {
// evaluate multiples of Starter vs Current
if ((i * j) % starter === 0) {
// When found evaluate next number in Range
starter = i * j;
break;
}
}
}
return starter;
}
console.log(smallestCommons([2,10])); // Result 2520
console.log(smallestCommons([23,18])); // Result 6056820