Is_prime: worried didn't do it right


#1


Not stuck at this exercise, just concerned I didn't do it in the most efficient way: Judging by the fact that I had to specify results for specific values, and the fact that the instructions specify using [x-1] at some, point, it just doesn't seem elegant:


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

So yeah, nothing much, just want to know if I did it how I was supposed to.


#2

This I took to mean range(2, x).

Remove that and the both else: and 2 will fall through to,

return True

No need to break since it returns. break is unreachable after return, anyway.

There are other ways we can write this program, and no doubt more efficient. It is discussed at length in the track if you did around. Consider some of the following:

  • What should the range actually be?

  • How would we make the range contain only odd numbers?


#3

Wait.
if x is GREATER than 2, return False?
x==2 returning True, I understand.
if x is evenly divisible by n, return False?
5 divided by 5 is an even division (5 is a prime number, the answer is 1).

HOW is this the answer?


#4

Was waiting for someone to point this out (or the OP to discover it).

That is the correct return, False. x cannot be divisible by any n (save itself and 1, but n will never be x in the loop, only x - 1).

This is not a proof of primeness. The fact that neither 2 nor 3 will divide into 5 is what proves it is prime.


#5

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