How Come In This Code To Find Prime Numbers, Is_prime(9) Returns True?
def is_prime(x): if x < 2: return False else: for n in range(2, x): if x % n == 0: return False else: return True print is_prime(9) ret
Solution 1:
This is because you don't actually loop, as you return True during the first cycle (9 % 2 == 0 is False).
Something like this should solve the problem:
defis_prime(x):
if x < 2:
returnFalsefor n inrange(2, x):
if x % n == 0:
returnFalsereturnTrue
Solution 2:
You can simplify the logic a good amount by keeping your original loop and not exiting early. You can add your first conditional to your final return:
defis_prime(x):
for n inrange(2, x):
if x % n == 0:
returnFalsereturn x > 2
BTW, the Sieve of Erastothenes is a pretty cool method of solving this problem in a much better run time complexity. Here's a link to a brief explanation:
Post a Comment for "How Come In This Code To Find Prime Numbers, Is_prime(9) Returns True?"