Oops, try again. Your function fails on is_prime(-7). It returns True when it should return False. Why is this happening?


#1




Oops, try again. Your function fails on is_prime(-7). It returns True when it should return False


-7 is prime so what can I do about this?


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


#2

Hi, @olibenham ,

Why are you using abs here? ...

if abs(x)<2:

Something to consider ... What is the value of abs(-7)?


#3

I was using abs because of the symmetry of the prime numbers and I thought it was a nice way to make the program shorter.

abs(-7)=7 which is a prime, so is_prime(-7) should return True and not False, as the error suggests.


#4

The error means that for -7, your is_prime function returned True when it should have returned False. Negative numbers are not considered prime. Since neither 0 nor 1 is prime, any number less than 2 is prime.

Since abs(-7), returns 7, which is prime, your function continues to execute, with the for loop testing the status of the number, 7, and ultimately returning True.

The abs function is not helpful to us here.


#5

Ah ,I see my error. Should have realised the negative numbers are not considered prime. Thanks for your assistance, managed to sort it out now.


#6