# Is_Prime

#1

Hello!

I’m not stuck on this assignment, but I was wondering if there was a better /more straight forward solution.
For example, I think I used too many loops in this function to avoid exceptions.

I believe there should be an easier way to do this assignment and although my codes work it should not be the most efficient way.

Here is my code:

``````def is_prime(x):
if x >= 0:
for i in range (2, x+3): # because I wanted to make sure I wouldn't have a problem with an "null" range when x = [0,1,2]
if x != i:
if x % i == 0 or x == 1 :
return False
break

else:
return True
else:
return False
``````

I also thought about limiting the range to the square root of x (since if the number is prime, it should not be dividable by the numbers smaller than the square root of x) but I’m wondering if it’s helpful and actually increases the efficiency of the program.
(I want to replace the first couple of lines with the following code : )

``````from math import sqrt
def is_prime(x):
if x >= 0:
sqrt_x = int(sqrt(x))
for i in range (2,sqrt_x+3):
``````

Thanks!

#2

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