ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: Prime sieve generators
Submitter: Aaron Gallagher (other recipes)
Last Updated: 2008/04/25
Version no: 1.3
Category: Algorithms

 

Not Rated yet


Description:

Two simple generators for generating prime numbers using a prime sieve. gen_sieve(n) will produce all prime numbers
isprime is an example of how one could use gen_sieve: a quick function for testing primality by attempting modulo division with each potential prime factor of a number.

Source: Text Source

import math

def gen_sieve(ceiling=None):
    if ceiling is not None:
        if ceiling % 2 == 0:
            ceiling -= 1
        highest_prime = math.ceil(math.sqrt(ceiling))
    last_val = 1
    found_primes = []
    yield 2
    while ceiling is None or ceiling > last_val:
        current_val = None
        while current_val is None:
            current_val = last_val = last_val + 2
            for prime, square in found_primes:
                if current_val < square: 
                    break
                if current_val % prime == 0:
                    current_val = None
                    break
        yield current_val
        if ceiling is None or highest_prime > last_val:
            found_primes.append((current_val, current_val ** 2))

def isprime(n):
    for fac in gen_sieve(int(math.ceil(math.sqrt(n)))):
        if n % fac == 0 and n != fac:
            return fac
    return 0

Discussion:

This is the fastest prime sieve I could come up with in python. There might be a way to reduce the memory footprint.



Add comment

Number of comments: 2

2 is prime, Ron Reeder, 2008/04/15
2 is a prime number... Your algorithm says it's not. I ran it using the following code: ---
def main(): testnos = (1,2,3,4,5,6,7,8,9,10,11,12,13,41) for testno in testnos: factor = isprime(testno) if factor: print ("Number is not prime: %i - factor is: %i\n" % (testno,factor)) else: print ("Prime Number! - %i\n" % testno) if __name__ == '__main__': main()
Output: Prime Number! - 1 Number is not prime: 2 - factor is: 2 Prime Number! - 3 Number is not prime: 4 - factor is: 2 Prime Number! - 5 ...
Add comment

Aaron Gallagher, 2008/04/25
Oh, whoops! I didn't catch that before. It should be fixed now.
Add comment



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. Wrapping template engine ...

4. Assignment in expression

5. SOLVING THE METACLASS ...

6. Povray for python

7. Calling Windows API ...

8. Generic filter logic ...

9. Function Decorators by ...

10. MS SQL Server log monitor




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.