I’m not a math, js expert. but I believe your code doesn’t follow a good and logical algorithm.
First is about sorting out your array in for loop. You Should not sort the array every iteration, and you may sort it once you pushed elements on it(after for loop).
Second issue could be about you j++
. (again I’m not mathpants), but I think it’s redundant to check range of min to max(exclusive) where max is the largest number in your array(check condition), considering following example:
you go for [1,6], here min is 1 and max is 6
Your while, you start it from 1, and check if it’s okay 1%elems_on_arr which fails becasue of 2.
Then you add 1 to j, now j is 2, but next iteration will fail becasue of 3 this time
Then you add 1 to j, now j is 3, but next iteration will fail becasue of 4 this time
The above logic till maximum number of your array.
So it’s better start from maximum number of array, and not add one by one, instead add it by max value.
var j = Math.max(...arr);
...
j+=Math.max(...arr);
Beside that I still think adding maximum value to current value and try again is not logical, becasue consider 17 and 18, it starts from J=18, J%17 is 17, so here adding another 18(max) to J and try again is nonsense, becasue for next 17 iteration it will not J%17===0.
Another thing could be about dividable small elements to larger elements. For example when your array has 2,3,4,…,8, and you add max(8) to each iteration, you should not check for 2, and 4, since they are divisible to 8, Same about 3 becasue you have 6.
So this is better check array elements divisibility to max value before you go for checking process.
Same checking the the result with max value is redundant, since you add 8 at each iteration, so it will always true.
About the math, you should ask some math expert, but indeed if I got some stuff in my mind about it, will help of course.
Same about js, if you just add one console.log("no way")
after your while(true){}
block you realized for the one failed test ([23, 18]
) this line is triggered which is not expected! I’m not js expert, but I think browser may ignore the while since it’s too much already(exceeded process) and just ignores the rest of the while.
You should come up with better algorithm, to make it lighter, so your while loop never get ignored, and result the correct value.
I hope I could come up with the solution. The only thing I know is it’s easy becasue I can understand it, but should come up with the solution(sorry lack of math stuffs)
For now I suggest you apply the optimization and logical changes I stated.
Keep going on great work, happy programming.