0

# Prime numbers

nextPrime: for (var i = 2; i < 10; i++) { for (var j = 2; j < i; j++) { if (i % j == 0) continue nextPrime; } alert( i ); // prime } Who can explain how this code works? When variable j is being increased?

1 Answer

+ 3

The variable j is increased in the (inner) for j-loop and gets resetted in every loop of the first (outer) for i-loop.
For every number i from 2 to 9 the modulo with every number j from 2 to i-1 is calculeted. If a i modulo j result of 0 is found, the number i can be divided by j, so it isnt a prime and the next number will be tried.
If there is no modulo result equals zero the number will be alerted as a prime.