Ucode2
Ucode2

Reputation: 82

how nested loop works in the following example

I have a code for printing all prime numbers lying in the range (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.

Upvotes: 0

Views: 69

Answers (3)

user12532854
user12532854

Reputation:

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')

Upvotes: 1

Kashyap KN
Kashyap KN

Reputation: 419

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.

Let's go through step by step for a prime and a non-prime number.

Example 1 : Prime number 7(Assume value of i is at 7 in the for loop)

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. Let's say 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.

Upvotes: 1

user3088903
user3088903

Reputation: 41

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.

Hint, do it for i = 39.

Upvotes: 0

Related Questions