What is going on in this while loop?

Continuing the discussion from freeCodeCamp Challenge Guide: Smallest Common Multiple:

I am studying the solution to get better at solving this problem, but this while loop has me confused. What is the loop doing for each iteration?

while ((num % i) === 0) => while numer is even

The line factors[i] = (factors[i]) ? factors[i] + 1 : 1; uses a ternary operator to increment the value of factors[i] by 1 if it already exists (i.e., it is truthy), or set it to 1 if it doesn’t exist yet (i.e., it is falsy). This line effectively counts the number of times “i” appears as a factor of “num”.

num /= i; devides num by it’s index

1 Like

given whats already been said, here is my two bits

  • keeps track of occurrence of factor, as in which number is just matched num % i === 0
  • if you recall, any loop requires its “iterator - as in whats next to work with”, this here also does that same by "dividing it by its “preceding loop index”, so that this “while” loop can come to an end at some point

hope this was helpful, happy learning :slight_smile:

I would only look at the solutions once you have an answer of your own. It’s easier to see what the solutions do in that case.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.