Hey,
First timer. Anyone care to help me? I’m currently doing intermediate algorithm challenges. This one on finding the smallest common multiple for a range of numbers stumped me. This is my attempt below. I tried to add comments, but if any part of it isn’t clear, please let me know. My code works for all test inputs, except [1, 13] and [18, 23]. I honestly couldn’t figure out why.
Sorry if this is too long, as I’ve never done this before. Any tips or suggestions would be greatly appreciated!
function smallestCommons(arr) {
// find the range of numbers
arr.sort((x, y) => x - y);
let range = [];
let i = arr[0];
while (i < arr[1] + 1) {
range.push(i);
i++;
}
// divide n by each number in the range
let n = 2;
for (let i = 0; i < range.length; i++) {
if (n % range[i]) {
// if n doesn't divide evenly, then increment n and start over
i = 0;
n++;
}
}
return n;
}