6. is_prime(0 Task. Help needed with negative primes


#1

I have created a function that checks if a number is prime, however it returns -7 as False instead of True. Here is my code:
def is_prime(x):
if abs(x) > 3:
for n in range(2,abs(x),1):
if abs(x) % n == 0:
return False
else:
return True

elif abs(x) == 0:
    return False

elif abs(x) == 1:
    return False

else:
    return True

#2

In your code, for loop won't run for negative number..
lets suppose x is -7 now range (2,-7,1) will not run for even single iteration.

You can handle negative number like that:

if ('-' in str(x)):
for n in range(x,-2,1):
    if abs(x) % n == 0:
        return False
    else:
        return True

else:
for n in range(2,abs(x),1):
if abs(x) % n == 0:
return False
else:
return True

Hope this helps!!


#3

Working code :smiley:

def is_prime (x):
    if x < 2 :
        return False
    for n in range(2, x + 1):
        if x / n == 1 :
            return True
        elif x % n == 0 :
            return False