Your algorithm is less efficient as it could be, so it is taking a bit longer for it to complete. It does get the correct answer though. If the tests take too long, it is assumed there may be a infinite loop and your solution is tripping the infinite loop protection. You can add the following comment to the top of your code and it will turn off this protection for this solution.
You could declare tester = true; before starting the while loop.
var tester = true;
while (tester) {
cmmd++;
tester = rangeArr.every(x => cmmd % x === 0) ? false : true;
}
or just declare tester with no value which will make it undefined and then reverse your while loop condition logic and swap the true and false in your ternary statement.
var tester; // undefined
while (!tester) {
cmmd++;
tester = rangeArr.every(x => cmmd % x === 0) ? true : false;
}
Thank you guys. Very constructive comments.
I was aware that my algorithm is not that efficient, I did not look up the math formula for this task. I wanted to see if I am able to come up with a solution of my own.
Based on your comments, I have made some small corrections to my code, but still I had to use the “// noprotect” to be able to pass the tests.
function smallestCommons(arr) {
arr = arr.sort((a,b) => a-b);
var len = arr[1] - arr[0] + 1;
var cmmd = arr[arr.length - 1] * arr[arr.length - 1];
var rangeArr = [];
for (var i = 0; i < len; i++) {rangeArr.push(arr[0] + i);}
var tester = true;
while (tester) {
cmmd ++;
tester = !rangeArr.every(x => cmmd % x == 0);
}
return cmmd;
}
smallestCommons([1,5]);
Thanks a lot and keep up with your comments. It helps a lot a beginner like me