Smallest Common Multiple do not pass last challenge

Smallest Common Multiple do not pass last challenge
0

#1

Can someone help me by inspecting my code and let me know why it does not pass the challenges.
Thanks

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 = new Array(len).fill(arr[0]).map((x,ind) => x + ind);
	var tester = rangeArr.every(x => cmmd % x == 0) ? false : true;
	while (tester) {
		cmmd ++;
		tester = rangeArr.every(x => cmmd % x == 0) ? false : true;
	}
	return cmmd;
}

smallestCommons([1,5]);

#2

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.

// noprotect

Smallest Common Multiple - test bug?
#3

On a side note, you could avoid the following duplicate code in two different ways:

tester = rangeArr.every(x => cmmd % x === 0) ? true : false;

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;
  }

#4

rangeArr.every(x => cmmd % x === 0) already returns either true or false,
you don’t need ? true : false part.


#5

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 :slight_smile: