'Python prime number find [closed]

def isPrime(x):
    for i in range(2,x):
       if x%i==0:
          return 'not prime'
          break
       else:
          return 'prime'
print(isPrime(15))

Hello, 15 is not a prime number but it outputs that it is prime, where is the mistake?



Solution 1:[1]

  • the position of "else" is wrong, you should put it when the for loop ends.
def isPrime(x):
    if x in [2,3]  :
        return "prime"
    for i in range(2,x): 
        if x%i==0:
            print(i)
            return 'not prime'
    return "prime"
print(isPrime(15))

Solution 2:[2]

Here, when you start looping using the for loop your first instance of integer "i" will be i=2, and hence 15%2 is obviously not equal to 0, hence it moves to the else logic condition and prints prime without proceeding further which causes it to print prime and then exit your program.

Here is the correct program just in case you want to see one approach on how to do it:

def isPrime(n) : 

# Corner cases 
if (n <= 1) : 
    return False
if (n <= 3) : 
    return True

# This is checked so that we can skip  
# middle five numbers in below loop 
if (n % 2 == 0 or n % 3 == 0) : 
    return False

i = 5
while(i * i <= n) : 
    if (n % i == 0 or n % (i + 2) == 0) : 
        return False
    i = i + 6

return True

Solution 3:[3]

Your Else should be out of the looping otherwise the i will be equal to 2 only.
The code should be like this:

def isPrime(x):
    for i in range(2,x):
       if x%i==0:
          return 'not prime'
          break
     else:
        return 'prime'
print(isPrime(15))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 ABDULAZIZ NOREDIN QADMOR