I think the code is correct, why's the error?


#1

In exercise 6. is_prime I am using this code:



def is_prime(x):
  if (x-1) % 2 == 0 and x != 1:
    return True
  elif x == 1:
    return False
  else:
    return False 


it keeps showing me an error that the function does not work with 2 like when you use is_prime(2). The error says that it returns False when it should return True but that’s wrong because 1 is not a prime number.
so what’s the deal?


#2

Why x - 1? If the code is correct then it should return the correct value (False) when given a non-prime, like 9.

>>> def is_prime(x):
  if (x-1) % 2 == 0 and x != 1:
    return True
  elif x == 1:
    return False
  else:
    return False

>>> is_prime(9)
True
>>> 

Your code is essentially letting all odd numbers be prime, which we know is not the real case. All primes are odd, (except 2) but not all odds are prime.


#3

oh, guess I need to refresh my math a little since I thought this is how you get a prime number


#4

The exercise suggests a brute force approach that uses trial division.

if x < 2: return False

That being the first line of your function block, will rule out any number less than 2. Now we can begin iterating over a range and doing the trial division.

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

Primes are not divisible by any number except themself and 1. Should any value for x prove divisible, we know it is not prime, so return False.

Lastly,

return True

This will catch the 2 from the first if statement (since it will not make it into the loop), and also any numbers that trickle down from the loop.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.