Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #50381

Re: Prime number generator

Path csiph.com!usenet.pasdenom.info!news.albasani.net!newsfeed.freenet.ag!news2.euro.net!newsgate.cistron.nl!newsgate.news.xs4all.nl!post.news.xs4all.nl!not-for-mail
Return-Path <ian.g.kelly@gmail.com>
X-Original-To python-list@python.org
Delivered-To python-list@mail.python.org
X-Spam-Status OK 0.002
X-Spam-Evidence '*H*': 1.00; '*S*': 0.00; 'else:': 0.03; 'root': 0.05; 'discard': 0.07; 'initialize': 0.07; 'odd': 0.07; 'tries': 0.07; 'below).': 0.09; 'implements': 0.09; 'none)': 0.09; 'noted,': 0.09; 'subject:number': 0.09; 'def': 0.12; '2):': 0.16; 'collections': 0.16; 'count,': 0.16; 'defaultdict': 0.16; 'dict': 0.16; 'dig': 0.16; 'doubles': 0.16; 'generator.': 0.16; 'integer,': 0.16; 'itertools': 0.16; 'multiples': 0.16; 'subject:Prime': 0.16; 'subject:generator': 0.16; 'threshold': 0.16; 'wrote:': 0.18; 'wed,': 0.18; 'later': 0.20; '(the': 0.22; 'import': 0.22; 'skip': 0.24; 'header:In-Reply-To:1': 0.27; 'am,': 0.29; 'message-id:@mail.gmail.com': 0.30; '(since': 0.31; 'factor': 0.31; 'another': 0.32; "can't": 0.35; 'received:google.com': 0.35; 'add': 0.35; 'marks': 0.36; 'yield': 0.36; 'done': 0.36; 'next': 0.36; 'entry': 0.36; "i'll": 0.36; 'starting': 0.37; 'to:addr:python-list': 0.38; 'previous': 0.38; 'rather': 0.38; 'to:addr:python.org': 0.39; 'ian': 0.60; 'numbers': 0.61; 'first': 0.61; 'reach': 0.63; 'generated.': 0.68; 'records': 0.73; 'jul': 0.74; 'prime': 0.74; 'square': 0.74; 'excessive': 0.84; 'factors,': 0.84; 'tossing': 0.84; 'yielded': 0.84; 'composite': 0.91; 'factors': 0.97; '2013': 0.98
DKIM-Signature v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20120113; h=mime-version:in-reply-to:references:from:date:message-id:subject:to :content-type; bh=9BKkJsnPi8TgyPxOmUprA9SDdAuV/DVrWhtlTVwTlL4=; b=zUFpY0iGG7I98lvsgeFJHa+tx3k3NplzKgN23E+aAbhIew08DKSrFQGTbj7i369sil SQZ4oIa2wrknoE8+xqu9v2/CobBEJVTo0xClvP6ERnw8QYcRGsvqibjuDxChqewGcz9H m58flIP4Od6pvRHunVNxDUs3O2ufMcf3uNE+RbyMwwhfKRYIG1B0PulDU8H1I5EozPx2 rH/cBWmTFA5SbcYXfqmdUHywwPYpisV6guUH0HlGJQ77xzT4s9UZaBYecwSslUIi5gqA IZ6y4aU0mcmCC5WaxPd3AKVwuZD+K8vWeIYhYJmWSzDeOCJdZpduSGV/OHORrVAlYzVX PujQ==
X-Received by 10.68.217.7 with SMTP id ou7mr32534252pbc.8.1373475315186; Wed, 10 Jul 2013 09:55:15 -0700 (PDT)
MIME-Version 1.0
In-Reply-To <CALwzidmy-CZYOZ2hdcssOWOZ+U8GVv8MrcjG0LD6TtwbdhBX6w@mail.gmail.com>
References <CAPTjJmq_7+rtNV22cxpLXQ+G1XfCyJvKckN+2B3PjfVEEs-5Qw@mail.gmail.com> <CALwzidmy-CZYOZ2hdcssOWOZ+U8GVv8MrcjG0LD6TtwbdhBX6w@mail.gmail.com>
From Ian Kelly <ian.g.kelly@gmail.com>
Date Wed, 10 Jul 2013 10:54:35 -0600
Subject Re: Prime number generator
To Python <python-list@python.org>
Content-Type text/plain; charset=ISO-8859-1
X-BeenThere python-list@python.org
X-Mailman-Version 2.1.15
Precedence list
List-Id General discussion list for the Python programming language <python-list.python.org>
List-Unsubscribe <http://mail.python.org/mailman/options/python-list>, <mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive <http://mail.python.org/pipermail/python-list/>
List-Post <mailto:python-list@python.org>
List-Help <mailto:python-list-request@python.org?subject=help>
List-Subscribe <http://mail.python.org/mailman/listinfo/python-list>, <mailto:python-list-request@python.org?subject=subscribe>
Newsgroups comp.lang.python
Message-ID <mailman.4539.1373475324.3114.python-list@python.org> (permalink)
Lines 50
NNTP-Posting-Host 2001:888:2000:d::a6
X-Trace 1373475324 news.xs4all.nl 15982 [2001:888:2000:d::a6]:44291
X-Complaints-To abuse@xs4all.nl
Xref csiph.com comp.lang.python:50381

Show key headers only | View raw


On Wed, Jul 10, 2013 at 10:16 AM, Ian Kelly <ian.g.kelly@gmail.com> wrote:
> The other interesting thing about my sieve is that it's a recursive
> generator.  I'll dig it up later and share it.

As promised.  Apologies for the excessive commenting.  As noted, this
implementation is a recursive generator, which is done so that the
primes in the sieve can go only up to the square root of the current
prime, rather than tossing in every prime seen so far.

from collections import defaultdict
from itertools import count, islice

def primes():
    yield 2
    # Set up the data structures.  multiples implements the sieve as a dict
    # that marks upcoming composite numbers and records the prime factors
    # that disqualified them.
    multiples = defaultdict(list)
    # subgen is a recursive sub-generator that supplies prime factors to be fed
    # into the sieve.  islice is used to skip 2 (since we only consider odd
    # numbers) and 3 (since we can't get it from subgen before we've yielded it
    # below).
    subgen = islice(primes(), 2, None)
    # Initialize the sieve with the first prime factor q.
    q = 3
    # When we reach threshold (the square of the last prime added to the sieve),
    # it's time to add another prime to the sieve.  By construction, threshold
    # is always an odd composite.
    threshold = q * q
    multiples[threshold].append(q + q)
    # The main loop tries every odd integer, starting with 3.
    for p in count(3, 2):
        if p in multiples:
            # p is composite.  Discard the entry from multiples and mark the
            # next odd multiple of each prime factor that disqualified p.
            # Because the multiples dict actually stores the doubles of the
            # prime factors, they need only be added once to get to the next
            # odd multiple.
            for q in multiples[p]:
                multiples[p + q].append(q)
            del multiples[p]
            if p == threshold:
                # All primes up to the previous q ** 2 have been generated.
                # Get the next prime factor q and add it to the sieve.
                q = subgen.next()
                threshold = q * q
                multiples[threshold].append(q + q)
        else:
            # p is prime.  Yay!
            yield p

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Prime number generator Ian Kelly <ian.g.kelly@gmail.com> - 2013-07-10 10:54 -0600

csiph-web