In Wikipedia, this is one of the predefined algorithms for generating prime numbers:
def eratosthenes_sieve(n): # Create a candidate list within which non-primes will be # marked as None; only candidates below sqrt(n) need be checked. candidates = [i for i in range(n + 1)] fin = int(n ** 0.5) # Loop over the candidates, marking out each multiple. for i in range(2, fin + 1): if not candidates[i]: continue candidates[i + i::i] = [None] * (n // i - 1) # Filter out non-primes and return the list. return [i for i in candidates[2:] if i]
I changed the algorithm a bit.
def eratosthenes_sieve(n): # Create a candidate list within which non-primes will be # marked as None; only candidates below sqrt(n) need be checked. candidates = [i for i in range(n + 1)] fin = int(n ** 0.5) # Loop over the candidates, marking out each multiple. candidates[4::2] = [None] * (n // 2 - 1) for i in range(3, fin + 1, 2): if not candidates[i]: continue candidates[i + i::i] = [None] * (n // i - 1) # Filter out non-primes and return the list. return [i for i in candidates[2:] if i]
First I highlighted all the multiples of 2, and then I looked at the odd numbers. When I timed both algorithms (tried 40,000,000), the first one was always better (although very little). I do not understand why. Can someone explain?
PS: When I try 100,000,000, my computer freezes. Why is this? I have a Core Duo E8500, 4 GB of RAM, Windows 7 Pro 64 bit.
Update 1: this is Python 3.
Update 2: so I was configured:
start = time.time() a = eratosthenes_sieve(40000000) end = time.time() print(end - start)
UPDATE:. From valuable comments (especially the nightmare and Winston Evert), I was able to determine what I intended in the first place:
def eratosthenes_sieve(n): # Create a candidate list within which non-primes will be # marked as None; only c below sqrt(n) need be checked. c = [i for i in range(3, n + 1, 2)] fin = int(n ** 0.5)
This algorithm improves the original algorithm (mentioned above) by 50%. (However, worse than the algorithm mentioned by the night scraper, of course).
Question for Python Masters: is there a more Pythonic way to express this last code in a more functional way?
UPDATE 2: I still could not decode the algorithm mentioned by the night scraper. I guess I'm too stupid.