Home > Enterprise >  why is 3 not prime number? This is from W3S , and it would be better, I agree that iterator is divid
why is 3 not prime number? This is from W3S , and it would be better, I agree that iterator is divid

Time:02-26

Function to identify is n prime or not.

def test_prime(n):
  
    if n == 1:
        return False
    elif n==2:
        return True
    else:
        for e in range(2,n): # iteration from 2 to n
            if e % 2 == 0:
                return False
        return True

Why is 3 not prime number here?

  print(test_prime(3))

CodePudding user response:

That is because the logic you have implemented is wrong. As it is already pointed out, your code currently is checking whether or not your input number is even or odd. For checking if the number is prime, you can do as follows:

def test_prime(n):
  
    if n == 1:
        return False
    elif n==2:
        return True
    else:
        for e in range(2,n): # iteration from 2 to n
            if n % e == 0:
                return False
        return True

The else condition will check whether the remainder after dividing the input number by each number in range is 0 or not. If it's 0 then it's not a prime number. Also, you could run the loop from 0 to half of n, which is more efficient as suggested.

  • Related