Show HN: Prime number sieve in 31 lines of Python
github.com
github.com
In contrast, a C++ implementation would take under 1s. Considering the standard Python multiplier of 5x-10x, that’s still a maximum of 10 seconds for a well-written implementation. And that’s the standard implementation with no fancy tricks.
Sometimes brevity is just not worth it...
Here's a naive implementation I just wrote:
def crible(n):
nums = [True] * n
nums[:1] = [False, False]
for i, isPrime in enumerate(nums):
if not isPrime:
continue
yield i
j = 2
while i*j < len(nums):
nums[i*j] = False
j += 1
It is much faster (and is about 10 lines of Python): timeit.timeit("list(crible(1000000))", number=1, globals={'crible': crible})
0.9441672329999165