检查质数的简单说明

我想请人解释一下,这段代码如何工作?因为我无法完全理解。 此代码在控制台中写入2到n之间的所有素数。

let n = 10;

nextPrime:
for (let i = 2; i <= n; i++) {
   for (let j = 2; j < i; j++) {
      if (i % j == 0) continue nextPrime;
   }
   console.log(i);
}
评论
ysit
ysit

质数是一个可以除以1的数字,它本身没有除数。

This code loops over <2...n) range to check if the number can be divided by it (i % j == 0). If it can be divided by that number, it means that i is not a prime number, so we continue nextPrime, which means ending current iteration and proceeding to the next one. If we never run continue for particular j, it means it's a prime number.

点赞
评论