Error in loop / javascript euler# 5

I tried solve the problem to find the first integer that is divisible by all the numbers from 1 to 20 inclusive, but my program went into an infinite loop. Please tell me where are my mistake and how to fix it, thanks in advance.

var number = 0;
var test = false;

while (test === false) {
  for (var i = 1; i <= 20; i++) {
    if (number % i === 0) {
      continue;
    } else {
      break;
    }
    test = true;
  }
  number += 20;
}
console.log(number);

Upvotes: 0

Views: 54

Answers (3)

davidhu
davidhu

Reputation: 10462

  for (var i = 1; i <= 20; i++) {
    if (number % i === 0) {
      continue;
    } else {
      break;
    }
    test = true;
  }

So, say the number is 17, i=1, the if statement is true, so we hit continue, which take us to the next iteration of the loop.

Then, i=2, the if statement is false, and we hit break, so we are out of the for loop.

Notice how you never hit the line that says test = true, so test is never true, and the loop continues, you just increment number by 20 each time.

Whenever we reach the end of the for loop or hit the break command, we reach the line number += 20, so number changes, but test does not.

So, here's my working solution

    var number = 0;
    var test = false;
    
    while (test === false) {
      test = true
      number += 20;
      for (var i = 2; i <= 20; i++) {
        if (number % i !== 0) {
          test = false;
          break;
        }
      }
    }
    console.log(number);

So, the logic behind this is once we are in the while loop, we assume that the number is what we are looking for, until the if statement evaluates to true and we are proven wrong. Then the while loop continues.

If we never run the code inside the if statement, then we have our answer.

Also, I incremented the number at the top of the while loop, otherwise you will have to subtract 20 from the final answer.

Upvotes: 1

Cool Dude
Cool Dude

Reputation: 1

You are using the break only to exit from for loop not the while loop. The while loop will always be true. That is the reason it is going to infinite loop

Upvotes: 0

Ilgorbek Kuchkarov
Ilgorbek Kuchkarov

Reputation: 95

if (number % i === 0) always null because you have number = 0 and when you divide 0 by any number remainder is always 0. Once number incremented by 20 you will have remainder and it will go to else clause. But there you are breaking the for loop and it is exiting before it is setting the test to true. So, test is always false. Your while loop is infinite

Upvotes: 1

Related Questions