gpt4 book ai didi

javascript - 以下程序是否在外循环的第一次迭代时执行嵌套循环?

转载 作者:行者123 更新时间:2023-11-30 14:07:47 24 4
gpt4 key购买 nike

在嵌套循环的第一次迭代中 i = 2j = 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
}
}

最佳答案

这是一张详细说明程序流程的图表:

+---+---+-------------------------------------------------------------+
| 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 = 2j = 2 时嵌套循环不执行,程序仍能运行。

关于javascript - 以下程序是否在外循环的第一次迭代时执行嵌套循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55084571/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com