My code doesn’t work for smallestCommons([23, 18]) for some strange reason; it’s not about the algorithm taking too much time (infine loop security) but the result is incorrect too. The result it gives is 2018940 (expected result is 6056820).
I found that: 6056820/2018940 = 3 (I don’t know if it helps)
function smallestCommons(arr) {
if (arr[1] < arr[0]) arr = [arr[1],arr[0]];
let num = arr[1];
let k = 1;
for (let i= arr[0]; i<=arr[1]; i++) {
if (num%i !=0) {
k++;
num = arr[1]*k; /* num must be a multple of arr[1] (biggest number -->
increases speed*/
i=arr[0];
}
}
return num;
}
That’s something you pretty much never want to do, and I never had seen a case for it in my experience.
Well, so why you just don’t create an array with all the number in that range, and loop over that?
Remeber that the final expression is executed after the body of a foor loop.
So what happens in your loop is
- i = 18
- 23 % 18 != from 0 --> YES
- set i back to 18
- loop-over
- for loop execute final expression, this means i = 19
- 23 % 19 !== 0 --> YES
- set i back to 18
- loop-over
- for loop execute final expression, this means i = 19
I know that you are updating other values in the loop condition, but your loop gets stuck until eventually you hit a number that is greater than 23, stopping the loop.
That doesn’t guaranteed that are all the number in the range.