Condition evaluating to true when it should evaluate to false

Hi, everyone!

Have a look at the following code, please:

function smallestCommons(arr) {
  let sortedArr = [...arr].sort((a, b) => a - b);

  let range = [];
  for (let i = sortedArr[0]; i <= sortedArr[1]; i ++) {
  let num = sortedArr[1]; 
  for (let c = 0; c < range.length; c ++) {
    if (num % range[c] !== 0) {c = 0; num += 1}
    if (c === range.length - 1) {console.log(num % c); return num}


I can’t seem to understand why it works in some cases and not in others. For example, if I pass the array [1, 13] as the argument -> console.log(smallestCommons([1, 13])), the function will produce the correct answer; however, that’s not the case for [18, 20] -> console.log(smallestCommons([18, 20])) and [23, 18] -> console.log(smallestCommons([23, 18])), as you can check by performing the operation inside the if loop. For example, [18, 20] returns 380, but console.log(380 % 18) === 2. I don’t know I’m there is anything I am overlooking. Could you help me figure out why it’s not working the way I expect it to?

Thank you very much!

This is correct, as 380/18 is 21.11111 so the modulus can’t be 0

It may be that your function is triggering the infinite loop protection and it is being stopped mid-way, and so you would need a less resource intensive function


Thank you, ieahleen. That seems to be the reason (I had to disable the time protection timeout but to no avail.

According to the internet the smallest common multiple of 18 and 20 is 180


@eoja What is your point?

Hi, eoja:

The point is to find the number which is evenly divided by X and Y, and all the numbers in between. for [18, 20], it would be X % 18 === 0, X % 19 ==== 0 and X % 20 === 0. :slightly_smiling_face:

common multiple of 18, 19 and 20 is 3420

@RandellDawson @sebasgrammar I understand the challenge and I made a mistake and planned up edit my answer to correctly provide as @ilenia did that 18, 19, 20 should come out to 3420. I was just trying to help provide what the expected result should be and, like I said, made a mistake. I apologize.