How to set proper terminal condition here

Lets say I have this function:

function divisibleTriangleNumber(n) {
  
    let triangCounter = 1;
    
    while (true) {
      let testedNumber = getNthTriangular(triangCounter);
      if (getNumberofDivisors(testedNumber) > n) {
        return testedNumber;
      }
      triangCounter++;
    }
    
  }

It’s working, and getting the job done for this Euler problem.
But I have no idea how do I set terminal condition for while loop here, I am running in this problems with while loop like all the time.

If you need more context for this code, I can post whole solution, with getNumberOfDivisors() and getNthTriangular() helper functions.

Ideally, the condition should be in the head of the while loop.

while (true) loops are a little scary and are usually used for user input prompt loops (if empty ask again) or maybe something like a game loop. Although then the true condition would likely be a boolean variable that can be given a name that explains it and can be changed to false.

while (isRunning)

The hint page solution has the functions return value as the condition for the loop if you need an example.

1 Like

I guess, that’s what I needed to hear, thanks.

I saw hint page before create this post. But wasn’t able to get logic from there to my code.

I guess I was a little bit confused because they are using loop to generate new triangle numbers, and I call function for that purpose(my function simply returns formula for nth triangle number).

However, I was able to rewrite code like this. Seems to work.

  function divisibleTriangleNumber(n) {
  
    let triangCounter = 1;
    let testedNumber = getNthTriangular(triangCounter);
    
    while (getNumberofDivisors(testedNumber) <= n) {
      triangCounter++;
      testedNumber = getNthTriangular(triangCounter);
    }
    return testedNumber;
  }

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