简体   繁体   English

以下示例中嵌套循环的工作原理

[英]how nested loop works in the following example

I have a code for printing all prime numbers lying in the range (2, 50)我有一个代码用于打印 (2, 50) 范围内的所有素数

num = 2
for i in range(2, 50):
    j = 2
    while(j <= (i/2)):
        if (i % j == 0):
            break
        j += 1
    if(j > i/j):
        print(i,'is a prime number')

My doubt is regarding the use and significance of if(j > i/j) statement.我的疑问是关于if(j > i/j)语句的使用和意义。

I haven't seen somebody use this algorithm for finding prime numbers before, you can do this for finding prime numbers:我以前没有见过有人使用这个算法来寻找素数,你可以这样做来寻找素数:

for i in range(2, 50):
    num, j = 0, 2
    while j <= i:
        if i % j == 0:
            num += 1
        j += 1
    if num == 1:
        print(i, 'is a prime number')

Based on the above, for all prime numbers by the time the code execution reaches if condition, j will always be equal to i and the if condition will become true.基于上述,对于所有素数,当代码执行达到 if 条件时,j 将始终等于 i,并且 if 条件将变为 true。

Let's go through step by step for a prime and a non-prime number.让我们一步一步通过 go 来获取素数和非素数。

Example 1: Prime number 7(Assume value of i is at 7 in the for loop)示例 1:素数 7(假设在 for 循环中 i 的值为 7)

i = 7
j = 2

# While statement condition check
2 <= 7/2 -> True
7%2 == 0 -> False

# Increment j, now j=3
7%3 == 0 -> False
.
.
# Increment continuously, and when j=7
7%7 == 0 -> True

#If Condition check(Current values are i=7 and j=7)
7 > 7/7 -> True

Example 2: Non-Prime Number.示例 2:非质数。 Let's say 9比方说 9

i = 9
j = 2

# While statement condition check
2 <= 7/2 -> True
9%2 == 0 -> False

# Increment j, now j=3
9%3 == 0 -> True

#If Condition check(Current values are i=9 and j=3)
3 > 9/3 -> False

Do try for other examples step by step to understand better.请逐步尝试其他示例以更好地理解。

Honestly the best way to understand things like this, is to break it down step-by-step yourself to understand it.老实说,理解这样的事情的最好方法是自己一步一步地分解它以理解它。 Take a smaller example, say range(2,6) , and write the progress/steps down by hand.举一个较小的例子,比如range(2,6) ,然后手动写下进度/步骤。

Hint, do it for i = 39 .提示,为i = 39做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM