Quantcast
Viewing latest article 17
Browse Latest Browse All 28

Answer by Ajay for Sieve of Eratosthenes - Finding Primes Python

By combining contributions from many enthusiasts (including Glenn Maynard and MrHIDEn from above comments), I came up with following piece of code in python 2:

def simpleSieve(sieveSize):    #creating Sieve.    sieve = [True] * (sieveSize+1)    # 0 and 1 are not considered prime.    sieve[0] = False    sieve[1] = False    for i in xrange(2,int(math.sqrt(sieveSize))+1):        if sieve[i] == False:            continue        for pointer in xrange(i**2, sieveSize+1, i):            sieve[pointer] = False    # Sieve is left with prime numbers == True    primes = []    for i in xrange(sieveSize+1):        if sieve[i] == True:            primes.append(i)    return primessieveSize = input()primes = simpleSieve(sieveSize)

Time taken for computation on my machine for different inputs in power of 10 is:

  • 3 : 0.3 ms
  • 4 : 2.4 ms
  • 5 : 23 ms
  • 6 : 0.26 s
  • 7 : 3.1 s
  • 8 : 33 s

Viewing latest article 17
Browse Latest Browse All 28

Trending Articles