python Eratosthenes的筛子。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Eratosthenes的筛子。相关的知识,希望对你有一定的参考价值。

import math
import sys


def factor(number):
    """
    Return list of prime factors for 'number'.
    """
    factors = []
    limit = int(math.sqrt(number))
    limit = limit if limit > 3 else 3
    primes = create_primes_generator(limit)
    for p in primes:
        while number % p == 0:
            number /= p
            factors.append(p)
            if number == 1:
                break
    return factors if factors else [number]


def create_primes_generator(limit):
    """
    Return prime numbers up to 'limit'.
    """
    if limit < 2:
        raise ValueError("Limit must be an integer 2 or larger.")
    # Cheat a bit, since we know that, other than 2, no other primes are even.
    yield 2
    pool = range(1, limit + 1, 2)[1: ]
    while (len(pool)):
        prime = pool[0]
        multiples = []
        # The sieve of Eratosthenes.
        for i in pool:
            if i % prime == 0:
                multiples.append(i)
        pool = set(pool)
        pool = pool.difference(set(multiples))
        pool = sorted(pool)
        yield prime


def main(number):
    """
    Arg 1 must be a positive integer.
    """
    factors = factor(number)
    print ', '.join([str(f) for f in factors])


if __name__ == '__main__':
    number = sys.argv[1]
    try:
        number = int(number)
        main(number)
    except Exception, e:
        print "Error: %s" % (e)
        print "Usage: python sieve.py positive_number"

以上是关于python Eratosthenes的筛子。的主要内容,如果未能解决你的问题,请参考以下文章

关于Eratosthenes筛子算法筛选小于n的素数的理解

每日一小练——Eratosthenes 筛选法

python sieve_of_eratosthenes.py

优化埃拉托色尼筛

GHC 分析文件和图表是矛盾的

在m和n之间生成素数[重复]