Is_prime - is this the best way?


#1

def is_prime(x):
    if x < 2:
        return False
    count = 0
    for n in range(2, x - 1):
        if x % n == 0:
            count = count + 1
    if count > 0:
        return False
    else:
       return True
    
  
print is_prime(9)

As you can see, I used if count > 0 along with if x % n == 0:
count = count + 1
to ensure that if there was at least one instance of a number dividing by x with no remainder, it would evaluate to False.

Is there a more efficient way of doing this check?


#2

From the standpoint of brute force, such as suggested in this exercise, efficiency is not the strong suit, but the code can be clearned up some. While it is feasible to count the occurrences of divisibilty and go from there, it is unnecessary. We want the first occurrence to short-circuit out of there, immediately.

if x % n == 0: return False

With the range starting at two, any even number will be ejected on the first pass.

Since 2 is locked out of the loop, and only values that have not been ejected will fall through it, there is no need for the else. Just a return statement.

return True

As for the range, in range(2, x) the upper limit is x - 1.


#3

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