Search code examples
pythonloopslogic

Printing prime number in python


I am trying to print prime numbers in python in the range 3-50. Here is the code:

for i in range(3,51):
flag=0
    for j in range(3,i):
        if(i%j==0):
            flag=1
    if(flag==0):
        print(i)

The code is running correctly except THAT IT IS ALSO PRINTING 4. Please tell if there is anything wrong with the logic of the code (ignore the efficiency issues).


Solution

  • change range(3,i) to range(2,i) because if we use range(3,i), 4 is not checked with division by 2. As a result 4 is returned as prime.

    for i in range(3,51):
        flag=0
        for j in range(2,i):
            if(i%j==0):
                flag=1
        if(flag==0):
            print(i)
    

    However, a more structural and efficient way is to use the following:-

    def isPrime(num):
        for i in range(2,num/2+1):
            if (num%i==0):
                return False
        return True
    
    for i in range(3,51):
        if isPrime(i):
            print i
    

    We don't need to check the division by all numbers till the number itself for prime. Because if we can check till the half of the given number only for increased efficiency.