Fabrizio (in cc) sta per mettere tutte le sue librerie aggiornate su
Bitbucket [tra parentesi le ha (abbiamo) usate per risolvere un tot di
problemi di Project Eulero].

Qui metto solo il suo sieve.py che ritengo uno dei piĆ¹ veloci esistenti,
Rabin e/o Miller compresi.

Ciao.
Marco.

-- 
http://beri.it/ - Un blog
http://beri.it/i-miei-libri/ - Qualche libro
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# --------------------------------------------------------------------------------
# LICENCE INFORMATIONS:
# --------------------------------------------------------------------------------
#
# THIS SOFTWARE** IS DISTRIBUTED UNDER THE MIT LICENSE:
# http://opensource.org/licenses/mit-license.php
#
# Copyright (c) 2011 Fabrizio Romano <sfab...@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

from __future__ import division, print_function
from math import ceil, sqrt
from itertools import takewhile

"""
The functions defined in this module assume the input they are passed is
correct. This is done because we need this library to be as fast as possible.
Checking the type of the input during one call to is_prime() wouldn't make that
big difference, but doing that on 10**7 calls would sure be significantly
slower. If you need to check the input for these functions, either do it in your
code before calling them or modify them.
"""

# small primes array
_smallp = ( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
           67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137,
           139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211,
           223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283,
           293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379,
           383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461,
           463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563,
           569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643,
           647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739,
           743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829,
           839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937,
           941, 947, 953, 967, 971, 977, 983, 991, 997)

def sieve(N):
    """Return a list of primes <= N.
    Exploit wheel criterion (dim: 30) and bit masks.

    >>> sieve(min(200, _smallp[-1]))
    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
    73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
    157, 163, 167, 173, 179, 181, 191, 193, 197, 199]
    >>> sieve(10**4)[:30]
    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
    73, 79, 83, 89, 97, 101, 103, 107, 109, 113]
    >>> sieve(10**4)[-30:]
    [9733, 9739, 9743, 9749, 9767, 9769, 9781, 9787, 9791, 9803, 9811, 9817,
    9829, 9833, 9839, 9851, 9857, 9859, 9871, 9883, 9887, 9901, 9907, 9923,
    9929, 9931, 9941, 9949, 9967, 9973]
    >>>
    """

    const = 30 # wheel: 2*3*5
    if N < 2:
        # no primes smaller than 2
        return []
    if N <= _smallp[-1]:
        # no need to calculate, we just use a part of _smallp
        return list(takewhile(lambda p: p<=N, _smallp))
    # offsets list:
    # if you write a number as 30k + c, foreach k there are only 8 numbers that
    # could be primes: c = 1, 7, 11, 13, ...
    offsets = (1, 7, 11, 13, 17, 19, 23, 29)
    # prepare the prime list
    p = [2, 3, 5]
    dim = 1 + N // const # we need about 1/30 of the original dimension
    # To be Parsed list
    tp  = [0b11111111] * dim
    m1,m7,m11,m13,m17,m19,m23,m29=1,1<<1,1<<2,1<<3,1<<4,1<<5,1<<6,1<<7
    tp[0] &= ~m1
    # help dictionary d
    # d[a , b] = c  ==> if we want to find the smallest useful multiple of
    # (30*pos)+a on tpc, we need the index given by the product of
    # [(30*pos)+a][(30*pos)+b] in general.
    # If b < a, we need [(30*pos)+a][(30*(pos+1))+b]
    d = {}
    for x in offsets:
        for y in offsets:
            res = (x*y) % const
            if res in offsets:
                d[(x, res)] = y
    # another help dictionary TeMP Masks
    tmpm = {1:~m1, 7:~m7, 11:~m11, 13:~m13, 17:~m17, 19:~m19, 23:~m23, 29:~m29}
    pos, prime, stop = 0, 0, int(ceil(sqrt(N)))
    # inner parser
    def del_mult(mk, start, step):
        for k in xrange(start, len(tp), step):
            tp[k]&=mk # this is already ~m (see tmpm)
    cpos = const * pos
    # We could put these 8 blocks of code within another for cycle. We decided
    # not to do that because we want to avoid having to wait for other lookups.
    while prime < stop:
        # 30k + 1
        if tp[pos]&m1:
            prime = cpos + 1
            p.append(prime)
            kp = (prime*prime)//const
            for off in offsets:
                km = (d[(1, off)]*prime)//const
                if km < kp:
                    km += (1+(kp-km-1)//prime)*prime
                del_mult(tmpm[off], km, prime)
        # 30k + 7
        if tp[pos]&m7:
            prime = cpos + 7
            p.append(prime)
            kp = (prime*prime)//const
            for off in offsets:
                km = (d[(7, off)]*prime)//const
                if km < kp:
                    km += (1+(kp-km-1)//prime)*prime
                del_mult(tmpm[off], km, prime)
        # 30k + 11
        if tp[pos]&m11:
            prime = cpos + 11
            p.append(prime)
            kp = (prime*prime)//const
            for off in offsets:
                km = (d[(11, off)]*prime)//const
                if km < kp:
                    km += (1+(kp-km-1)//prime)*prime
                del_mult(tmpm[off], km, prime)
        # 30k + 13
        if tp[pos]&m13:
            prime = cpos + 13
            p.append(prime)
            kp = (prime*prime)//const
            for off in offsets:
                km = (d[(13, off)]*prime)//const
                if km < kp:
                    km += (1+(kp-km-1)//prime)*prime
                del_mult(tmpm[off], km, prime)
        # 30k + 17
        if tp[pos]&m17:
            prime = cpos + 17
            p.append(prime)
            kp = (prime*prime)//const
            for off in offsets:
                km = (d[(17, off)]*prime)//const
                if km < kp:
                    km += (1+(kp-km-1)//prime)*prime
                del_mult(tmpm[off], km, prime)
        # 30k + 19
        if tp[pos]&m19:
            prime = cpos + 19
            p.append(prime)
            kp = (prime*prime)//const
            for off in offsets:
                km = (d[(19, off)]*prime)//const
                if km < kp:
                    km += (1+(kp-km-1)//prime)*prime
                del_mult(tmpm[off], km, prime)
        # 30k + 23
        if tp[pos]&m23:
            prime = cpos + 23
            p.append(prime)
            kp = (prime*prime)//const
            for off in offsets:
                km = (d[(23, off)]*prime)//const
                if km < kp:
                    km += (1+(kp-km-1)//prime)*prime
                del_mult(tmpm[off], km, prime)
        # 30k + 29
        if tp[pos]&m29:
            prime = cpos + 29
            p.append(prime)
            kp = (prime*prime)//const
            for off in offsets:
                km = (d[(29, off)]*prime)//const
                if km < kp:
                    km += (1+(kp-km-1)//prime)*prime
                del_mult(tmpm[off], km, prime)
        pos += 1
        cpos += const
    # now complete for every other possible prime
    while pos < len(tp):
        # we don't do this: cpos = const * pos
        # we just add const on the last line so we spare a multiplication
        if tp[pos]&m1: p.append(cpos + 1)
        if tp[pos]&m7: p.append(cpos + 7)
        if tp[pos]&m11: p.append(cpos + 11)
        if tp[pos]&m13: p.append(cpos + 13)
        if tp[pos]&m17: p.append(cpos + 17)
        if tp[pos]&m19: p.append(cpos + 19)
        if tp[pos]&m23: p.append(cpos + 23)
        if tp[pos]&m29: p.append(cpos + 29)
        pos += 1
        cpos += const
    # remove exceeding if present
    pos = len(p) - 1
    while p[pos] > N:
        pos -= 1
    del p[pos+1:]
    # return p list
    return p
_______________________________________________
Python mailing list
Python@lists.python.it
http://lists.python.it/mailman/listinfo/python

Rispondere a