Can any one please explain this prime number code

Can any one please explain this prime number code
0

#1
var n = +prompt('enter the val');
nextPrime:
for(var i = 2; i <= n; i++) {
    for(var j = 2; j < i; j++) {
           if(i % j == 0) {
               console.log(i , j);
                continue nextPrime;
           }
      
    }
alert(i);
}

Now i do not understand for(var j = 2; j < i; j++) {

like why is j < i and will not i % j gives 0 as each time value is divided by itself , very confused here , kindly guide …

Thanks


#2

well it iterates from 2 to n, and for each number i from 2 to n it also iterates from 2 to that number - 1, hence why j < i, and checks if i can be divided by j without any remainder (like if i is say 7 it checks if 7 can be divided by 2, by 3, by 4, by 5 and by 6), if it’s the case it breaks iteration of the inner loop and types out in the console what broke it and proceeds the outer loop again, it’s only allowed to alert (i) if the inner loop wasn’t broken i.e. if the number was prime

not very effective btw, you should only iterate to the square root of the number…


#3

@ead thanks , so like for the first time inside j —

for(var j = 2; j < i; j++) {
           if(i % j == 0) {
               console.log(i , j);
                continue nextPrime;
           }

here both i and j are 2 so the loop body is ignored as 2/2 will give 0 remainder , i as 2 is printed and i is then taken as 3 …

here again 3/2 will not yield 0 but 3/3 will so again 3 is printed and i become 4, as j will start from 2 again…

here now again 4/2 will yield 0 so why is that being ignored …

I am really sorry for being confused as this is the way i am reading the code