From 18dbed16ae2585603340cdee580e86742078e021 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Izan=20Beltr=C3=A1n?= Date: Thu, 25 May 2017 23:01:32 +0200 Subject: [PATCH 1/2] Sieve of Eratosthenes optimization. Complexity and space reduced to a half. --- math/primes_sieve_of_eratosthenes.py | 38 +++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 7 deletions(-) diff --git a/math/primes_sieve_of_eratosthenes.py b/math/primes_sieve_of_eratosthenes.py index 6b8977614..00799d7cb 100644 --- a/math/primes_sieve_of_eratosthenes.py +++ b/math/primes_sieve_of_eratosthenes.py @@ -1,14 +1,38 @@ ''' Using sieve of Eratosthenes, primes(x) returns list of all primes less than x + +Modification: +We don't need to check all even numbers, we can make the sieve excluding even +numbers and adding 2 to the primes list by default. + +We are going to make an array of: x / 2 - 1 if number is even, else x / 2 +(The -1 with even number it's to exclude the number itself) +Because we just need numbers [from 3..x if x is odd] + +# We can get value represented at index i with (i*2 + 3) + +For example, for x = 10, we start with an array of x / 2 - 1 = 4 +[1, 1, 1, 1] + 3 5 7 9 + +For x = 11: +[1, 1, 1, 1, 1] + 3 5 7 9 11 # 11 is odd, it's included in the list + +With this, we have reduced the array size to a half, +and complexity it's also a half now. ''' def primes(x): - assert(x>=0) - sieve = [1 for v in range(x+1)] # Sieve - primes = [] # List of Primes - for i in range(2,x+1): - if sieve[i]==1: - primes.append(i) - for j in range(i,x+1,i): + assert(x >= 0) + # If x is even, exclude x from list (-1): + sieve_size = (x//2 - 1) if x % 2 == 0 else (x//2) + sieve = [1 for v in range(sieve_size)] # Sieve + primes = [2] # List of Primes + for i in range(0, sieve_size): + if sieve[i] == 1: + value_at_i = i*2 + 3 + primes.append(value_at_i) + for j in range(i, sieve_size, value_at_i): sieve[j]=0 return primes From f6103ff8732ecc95fd424a831e0ce71708cbdcfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Izan=20Beltr=C3=A1n?= Date: Fri, 26 May 2017 10:47:01 +0200 Subject: [PATCH 2/2] Fixed error for input 0, 1 Now return [] --- math/primes_sieve_of_eratosthenes.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/math/primes_sieve_of_eratosthenes.py b/math/primes_sieve_of_eratosthenes.py index 00799d7cb..34289da64 100644 --- a/math/primes_sieve_of_eratosthenes.py +++ b/math/primes_sieve_of_eratosthenes.py @@ -27,12 +27,14 @@ def primes(x): assert(x >= 0) # If x is even, exclude x from list (-1): sieve_size = (x//2 - 1) if x % 2 == 0 else (x//2) - sieve = [1 for v in range(sieve_size)] # Sieve - primes = [2] # List of Primes + sieve = [1 for v in range(sieve_size)] # Sieve + primes = [] # List of Primes + if x >= 2: + primes.append(2) # Add 2 by default for i in range(0, sieve_size): if sieve[i] == 1: value_at_i = i*2 + 3 primes.append(value_at_i) for j in range(i, sieve_size, value_at_i): - sieve[j]=0 + sieve[j] = 0 return primes