Introduction:
This Python code demonstrates the use of nested loops to find prime numbers between the range of 2 to 50. Prime numbers are numbers that are divisible only by 1 and themselves.
Code:
#Use of nested loops to find the prime numbers between 2 to 50
num = 2
for i in range(2, 50):
j= 2
while ( j <= (i/2)):
if (i % j == 0): #factor found
break #break out of while loop
j += 1
if ( j > i/j) : #no factor found
print ( i, "is a prime number")
print ("Bye Bye!!")
Logic:
- The code initializes a variable “num” with a value of 2.
- It then uses a for loop to iterate through the numbers from 2 to 50.
- Within the for loop, a variable “j” is set to 2.
- The code then enters a while loop that checks if “j” is less than or equal to half of “i”.
- If the condition is true, it checks if “i” is divisible by “j”.
- If a factor is found, the code breaks out of the while loop.
- If the loop completes without finding a factor, it means that “i” is a prime number.
Output:
>> 2 is a prime number
>> 3 is a prime number
>> 5 is a prime number
>> 7 is a prime number
>> 11 is a prime number
>> 13 is a prime number
>> 17 is a prime number
>> 19 is a prime number
>> 23 is a prime number
>> 29 is a prime number
>> 31 is a prime number
>> 37 is a prime number
>> 41 is a prime number
>> 43 is a prime number
>> 47 is a prime number
>> Bye Bye!!