Difficulty checking python prime

I am trying to get this code to work to return the input number as prime between 2 and 49, but all it does is return most of the numbers as prime even if they are not ... For the exercise, I was given that 3, 5 and 7 were the main ones, so just ignore this bit ...

def prime(a): if a < 2: return False if a % 2 == 0: return False if a == 3 or a == 5 or a == 7: return True for n in range(3,int(a ** 0.5) + 1): if a % n == 0: return False if a % n != 0: return True a = input("Enter a number between 1 and 49: ") if prime(a) is False: print a, " is not a prime number" if prime(a) is True: print a, " is a prime number" 
+4
source share
1 answer
 for n in range(3,int(a ** 0.5) + 1): if a % n == 0: return False if a % n != 0: return True # This if condition is not needed 

You do not need this condition 2 times. otherwise it will return immediately when the number is not divided by the current value of n . But you don’t want it. You need to check the following value if the current n cannot divide your number.

So, just remove this if and add return True after the loop ends.

So your prime() method should look like this: -

 def prime(a): if a < 2: return False if a % 2 == 0: return False if a == 3 or a == 5 or a == 7: return True for n in range(3,int(a ** 0.5) + 1): if a % n == 0: return False return True 
+5
source

Source: https://habr.com/ru/post/1440415/


All Articles