Is_prime problem: Isn't 7 a prime number ?! It gives me this message "Your function fails on is_prime(-7). It returns True when it should return False." Help


#1

This is my code, I don't understand the problem.

def is_prime(x):
x = abs(x)
if(x == 0 or x == 1):
return False
n = x - 1
while(n > 1):
if(x % n == 0):
return False
n -= 1
return True
print is_prime(int(raw_input("Give a number: ")))

The message I get is "Oops, try again. Your function fails on is_prime(-7). It returns True when it should return False."


#2

7 is but -7 is not. You are setting x=abs(x), which changes negative numbers to positive ones. This is an issue because negative numbers cannot be primes, but your code will just run the numbers as if they were positive. Try changing that up to make it so that numbers must be positive.


#3

Thank you very much for your response. Ok I'll fix that but why is it that negative numbers cannot be primes ?


#4

I would look this up for a better explanation, but basically prime numbers are always positive because they can only be multiplied by themselves and 1 to achieve the number. So 7 can only be achieved by multiplying 1 * 7 to equal 7, no other positive numbers can get you 7.

If you throw in negative numbers, you can now have 7*1 and -7*-1, so now 7 is no longer prime by the previous definition. In fact, every number that was prime now can have negative components, so there are no prime numbers that fit the original definition anymore.


#5

Got it.
Your help is much appreciated. Best regards :slightly_smiling:


#7

A post was split to a new topic: Primes - Why do the test cases involve 0 and negative numbers


#8