3 ms·
The is_prime implementation can be further trimmed down rather comfortably: def is_prime(i): if i < 4: return i >= 2 if i % 2 == 0: return False
by jcl 17y ago
The is_prime implementation can be further trimmed down rather comfortably:
def is_prime(i):
if i < 4: return i >= 2
if i % 2 == 0: return False
return all(i % x != 0 for x in range(3, int(math.sqrt(i)) + 1, 2))
Note that the Python implementation counts up by two at a time, as part of an optimization to avoid half of the primality tests. From my (limited) understanding of Clojure, the implementation in the article is counting up by one at a time, thereby doing twice the work and making the even check redundant, since you could otherwise simply write:
def is_prime(i):
return (i > 1 and all(i % x != 0 for x in range(2, int(math.sqrt(i)) + 1)))
Edit: The conditionals can be collapsed further, but it's starting to get silly:
def is_prime(i):
return (i == 2 or (i > 2 and i % 2 != 0 and all(i % x != 0 for x in range(3, int(math.sqrt(i)) + 1, 2))))