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?

4th Apr 2017, 6:39 AM
Risto Toivonen
Risto Toivonen - avatar
1 Réponse
+ 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.
4th Apr 2017, 7:22 AM
Daniel Thomalla
Daniel Thomalla - avatar