# Smallest Common Multiple challenge problem

What’s happening:
Hey, I’m stuck on the Smallest Common Multiple challenge. I got a sorted array, then got all necessary numbers from it and now I’m trying to check it for multiple ‘x’ it fails. Could you please give me a hint on why is it happening and what should I fix to avoid it?

My code

``````function smallestCommons(arr) {
var allNums = [];
var end = [];
arr = arr.sort();
for (var i=arr[0]; i<=arr[1]; i++) {
allNums.push(i);
}
allNums.forEach(function (elem, index){ //strange behaviour
for (var x=0; x<100;x++) {
if (elem%x === 0) {
end.push(x);
}
else end.push(false); //just for checks
}
});
return end;
}

smallestCommons([1,5]);``````

I’m not sure I understand your logic. Specifically, what is this trying to do?

``````    for (var x=0; x<100;x++) {
if (elem%x === 0) {
end.push(x);
}
else end.push(false); //just for checks
}
});
``````

I’m not sure what that approach does except to push a bunch of `false` and a few numbers into an array.

Everything up to that is sound. You just need an algorithm to use that data.

I like to start with the largest number for my loop. We know the the LCM must be a multiple of the largest number (like any other) but if we index with that, we get to the answer faster. So, set up some loops. In the outer loop, I increment my candidate LCM by my largest value (the last element in allNums.) In an inner loop, I check if each of the other elements in allNums is evenly divisible into my candidate. If any isn’t, I break out of that loop (no point checking the others) and increment the candidate and try it again. If I ever make it to the end of my inner loop, I know that that is the LCM and I return it.

Does that make sense?

Almost. As far as I understand it should be something like:
js

``````for (var x = arr[1]; x<100; x+=arr[1]) { //I still don't get what I should put as stop sign for loop - 100, 1000. 10000?
allNums.forEach (function(elem) {
if (elem%x === 0) {
return x;
}
else break;
}
}
``````

The “stop” number is the number you are trying to find, so you can’t really put something there. How about a while loop with some other condition to know when you have the LCM?

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (`</>`) will also add backticks around text.

1 Like

Like this?

``````var answer = 0;