在嵌套循环i = 2
和j = 2
的第一次迭代中。但是,嵌套循环的条件为j < i
。这是否意味着不执行嵌套循环?发生什么事了?
showPrimes(10);
function showPrimes(n) {
nextPrime:
for (let i = 2; i < n; i++) {
for (let j = 2; j < i; j++)
if (i % j == 0) continue nextPrime;
console.log(i); // a prime number
}
}
答案 0 :(得分:2)
以下是详细说明程序流程的图表:
+---+---+-------------------------------------------------------------+
| i | j | Notes |
+---+---+-------------------------------------------------------------+
| 2 | 2 | Nested loop condition is false. Hence, 2 is a prime number. |
| 3 | 2 | 3 is not divisible by 2. Let's keep searching. |
| 3 | 3 | Nested loop condition is false. Hence, 3 is a prime number. |
| 4 | 2 | 4 is divisible by 2. Hence, it's not a prime number. |
| 5 | 2 | 5 is not divisible by 2. Let's keep searching. |
| 5 | 3 | 5 is not divisible by 3. Let's keep searching. |
| 5 | 4 | 5 is not divisible by 4. Let's keep searching. |
| 5 | 5 | Nested loop condition is false. Hence, 5 is a prime number. |
| 6 | 2 | 6 is divisible by 2. Hence, it's not a prime number. |
| 7 | 2 | 7 is not divisible by 2. Let's keep searching. |
| 7 | 3 | 7 is not divisible by 3. Let's keep searching. |
| 7 | 4 | 7 is not divisible by 4. Let's keep searching. |
| 7 | 5 | 7 is not divisible by 5. Let's keep searching. |
| 7 | 6 | 7 is not divisible by 6. Let's keep searching. |
| 7 | 7 | Nested loop condition is false. Hence, 7 is a prime number. |
| 8 | 2 | 8 is divisible by 2. Hence, it's not a prime number. |
| 9 | 2 | 9 is not divisible by 2. Let's keep searching. |
| 9 | 3 | 9 is divisible by 3. Hence, it's not a prime number. |
+---+---+-------------------------------------------------------------+
希望这解释了为何即使i = 2
和j = 2
时嵌套循环都没有执行,程序仍能工作的原因。
答案 1 :(得分:0)
如果素数应该对素数返回true,对非素数返回false,那么当您检测到非素数时,只需返回false。正如评论所指出的那样,您不需要两个循环即可完成此操作。您可以简单地从2循环到n-1,尝试除法无余数。
答案 2 :(得分:0)
嵌套循环不在外部循环的第一次迭代中执行,即i == 2
时。在外部循环的第二次迭代中,我们有i == 3
,因此嵌套循环条件现在读取为j < 3
,因此它使用值j == 2
进行了一次评估。对于外循环的第三次迭代,我们有i == 4
,以便对嵌套循环的值2和3进行两次评估。依此类推。
希望有帮助-卡洛斯(Carlos)
答案 3 :(得分:0)
好吧,让我们逐步解释这个嵌套循环:
最初是i=2
和j=2
,因此将执行外部循环,但不会执行嵌套循环。跳过内部循环,它会在主循环2
console.log(i)
循环结束,i = 3
。这次j < i
是true
,因此嵌套循环开始。
在第一个嵌套循环i = 3
和j = 2
期间
continue
不会执行,i % j
不是0
,所以它结束并且j
增加。现在i=3
和j=3
以及嵌套循环退出并显示3
i=4
和嵌套循环,因为j=2
和j<i
。i % j
为true
。因此,这次将执行continue nextPrime
,外循环将再次以i = 5
开始。i = 5
,因此将执行嵌套循环。在嵌套循环中,j
的值为2
3
4
。它们中没有一个会引起continue
,因为5%2
5%3
或5%4
不是0
。在j
变成5
之后,嵌套循环将退出。它将打印i
,即5
。
continue nextPrime
做所有事情。它将检查i % j == 0
是否表示i
不是素数。因此它将通过i = i + 1
跳回到外循环,而不会最后跳到console.log()
showPrimes(6);
function showPrimes(n) {
nextPrime:
for (let i = 2; i < n; i++) {
for (let j = 2; j < i; j++){
console.log(`i:${i} j:${j}`)
if (i % j == 0) continue nextPrime;
}
console.log(`prime${i}`); // a prime number
}
}
为什么j
一次又一次地更改
因为它是一个局部变量,并且总是初始化为2
。它不仅限于内部循环。当内部循环结束时,它被销毁,在下一个循环中,由于2
for (let j = 2; ...
。