Tell us what’s happening:
The first solution I wrote (that I won’t share) gave good results until the last test. I looked up the topic on this forum and read about how it can stop your loop if the code isn’t efficient (it thinks it’s an infinite loop).
I couldn’t figure out how to do it more efficiently, so I looked ahead at the spoiler. The code I’m submitting now is based on that. In fact, as far as I can tell it does almost exactly the same thing in almost exactly the same order…
Your code so far
function smallestCommons(arr) {
arr.sort((a,b) => b-a);
let newArr = [];
for (let i = arr[0]; i>=arr[1]; i--) {
newArr.push(i);
}
let multi = 1;
let returnVal = 0;
let n;
do {
returnVal = newArr[0] * multi;
for (n=1; n<newArr.length; n++) {
if (returnVal % newArr[n] !== 0) {
multi++;
break;
}
}
} while (n !== newArr.length);
return returnVal;
}
And it still won’t pass the last test! Apparently, the loop is still terminating before the solution is found.
I tried changing the loop to this, which would require fewer iterations:
do {
returnVal = newArr[0] * multi * newArr[1];
for (n=2; n<newArr.length; n++) {
if (returnVal % newArr[n] !== 0) {
multi++;
break;
}
}
} while (n !== newArr.length);
And still, it won’t deliver the right results for that last test! And it still works fine for all the tests with smaller numbers!
What is going on? In what way is my code functionally different from the spoiler solution?
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple