Question

Could you please take a look at my implementation of the sieve of eratosthenes in Python and tell me how can I improve/optimize it?

I'm a beginner in programming, so I don't have any ideas how to optimize it, and I'd really appreciate it if you check it out and tell me what can be improved.

# -*- coding: utf-8 -*-
"""
Created on Fri Sep 27 19:57:14 2013

@author: stefan
"""
def sqrt_int(n):
    n = n**0.5
    if n == int(n):
        return True
    else:
        return False

def cbrt_int(n):
    n = n**(1.0/3)
    if n == int(n):
        return True
    else:
        return False

def sieve(limit):
    first_primes = [2,3,5,7]
    primes = [x for x in range (2,limit+1)]

    for y in first_primes:
        primes = filter(lambda x: x % y != 0, primes)

    primes = filter(lambda x: not sqrt_int(x), primes)
    primes = filter(lambda x: not cbrt_int(x), primes)

    if limit > 10: 
        primes = first_primes + primes
    else:
        primes = filter(lambda x: x <= limit, first_primes)
    return primes
Was it helpful?

Solution

Here is a much simpler version of the Sieve of Eratosthenes:

def primes(n): # sieve of eratosthenes
    ps, sieve = [], [True] * (n + 1)
    for p in range(2, n + 1):
        if sieve[p]:
           ps.append(p)
           for i in range(p * p, n + 1, p):
               sieve[i] = False
    return ps

There are ways to make that run faster without too much complexity. If you are interested in programming with prime numbers, I modestly recommend this essay at my blog.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top