Explain this part of code

Can any body explain this to me what this inner for loop does.
Why do we even need that.

 // Variables needed declared outside the loops.
  var quot = 0;
  var loop = 1;
  var n;

  // Run code while n is not the same as the array length.
  do {
    quot = newArr[0] * loop * newArr[1];
    for (n = 2; n < newArr.length; n++) {
      if (quot % newArr[n] !== 0) {
        break;
      }
    }

    loop++;
  } while (n !== newArr.length);

  return quot;

Full Code

If you open the Run Code link and add the console.log statement as below what is happening becomes more apparent.

  • quot is a ‘candidate’ for least common multiple - LCM
  • that loop tests this candidate to see if it is LCM of all (almost all - see below) in the range of numbers
  // Variables needed declared outside the loops.
  var quot = 0;
  var loop = 1;
  var n;

  // Run code while n is not the same as the array length.
  do {
    quot = newArr[0] * loop * newArr[1];
    for (n = 2; n < newArr.length; n++) {
      console.log(quot, newArr[n],quot % newArr[n] )
      if (quot % newArr[n] !== 0) {
        break;
      }
    }

    loop++;
  } while (n !== newArr.length);

  return quot;
Why skip the two largest?

The LCM of any two consecutive number is the product of those numbers. In case of [1,5] the LCM of 4 and 5 is 20. Any LCM for the entire range would have to be 20 or some multiple of 20 so there is no need to test these against every candidate.

That is also why in case of [1,5] number 20 was the first candidate for LCM
quot = newArr[0] * loop * newArr[1]; - effectively 4*1*5

What is it exactly checking

if (quot % newArr[n] !== 0){
 break;
}

if

reminder of quot/newArr[n]

isn’t equal to zero than break;
What good that will do?

look a bit higher… where is this code located? a loop…so what is happening to n as this code executes?

n is increasing by 1
But nothing is happening to quot which is the answer.

It’s breaking the loop. As soon as that conditional becomes true, it breaks out of the for loop and continue to the while loop, incrementing the loop index.

here you go

run this and you will see what is happening

1 Like

@hbar1st
Thanks for your help
Sadly, i didn’t solve it by myself.

i understand the sadness. But you learned something and that is the point of this. No one is expected to solve everything by themselves (all the time) in this field . That’s why we have colleagues and social networks etc to provide support.