我想请人解释一下,这段代码如何工作?因为我无法完全理解。 此代码在控制台中写入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);
}
我想请人解释一下,这段代码如何工作?因为我无法完全理解。 此代码在控制台中写入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);
}
质数是一个可以除以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 thati
is not a prime number, so wecontinue nextPrime
, which means ending current iteration and proceeding to the next one. If we never runcontinue
for particularj
, it means it's a prime number.