I was asked this problem in an interview a few days ago and wanted to improve on the solution I had given during it. So far this is what I have. Not sure how to go about making it more efficient. I guess for starters:
1) Does adding the i%2 == 0 line save time?
2) What is the time complexity of the % operator in python? Is there a way to check if a number is divisible by some faster way without using %?
3) The d <= math.sqrt(i) makes use of the fact that it is useless to compute divisors past the square root of i, as d will not divide i nicely until d=i. Does this present the optimal number of steps?
4) I start at d=3 because it's a given that i is odd
5) Going off the 4th point, I increment by 2 instead of 1, since it is a given that i is odd.
def is_prime(i):
if i < 2:
return False
if i == 2:
return True
d = 3
if i%2 == 0: #skip even numbers
return False
while d <= math.sqrt(i):
if i%d == 0:
return False
d += 2
return True