简体   繁体   English

在Python中优化素数生成器

[英]Optimizing a prime number generator in Python

I am looking for any suggestions on optimizing my prime number generator. 我正在寻找有关优化素数生成器的任何建议。 Could you please include the correction and a little comment on why it will be faster in your response. 您能否附上更正内容,并附上一些简短评论,说明其回复速度更快的原因。

def primeList ( highestNumber ):
""" This function takes a integer and returns a list of all primes less than or equal to that integer"""

    numbers = range( 2, highestNumber + 1 ) # creates an inclusive list of all numbers between 2 and highestNumber
    isPrime = [ True ] * len( numbers ) # each element corresponds to an element in numbers and keeps track of whether or not it is prime
    primes = [] # Where I'll build a list of prime numbers

    for i in range( len( numbers )  ):
        if ( isPrime[i] == True ):
            increment = numbers[i]
            position = i + increment
            primes.append( numbers[ i ] )

            while ( position < len( numbers )): # will only execute if the above if statement is true because position will still be greater than len( number )
                isPrime[position] = False  # Sets an element of isPrime to False if it is a multiple of a lower number
                position += increment   
    return primes

There's already a great discussion on various prime number generators here: Fastest way to list all primes below N 此处已经有很多关于质数发生器的讨论: 列出N以下所有质数的最快方法

At that link is a Python script that you can use to compare your algorithm against several others. 在该链接处是一个Python脚本,您可以将其与其他几种算法进行比较。

You can remove the even numbers greater than 2 from your "numbers" list because surely those even numbers are not prime so you don't have to check them. 您可以从“数字”列表中删除大于2的偶数,因为这些偶数肯定不是质数,因此您不必检查它们。 You can do this by setting the step parameter of the range function. 您可以通过设置范围功能的step参数来实现。

def primeList ( highestNumber ):
    """ This function takes a integer and returns a list of """
    """ all primes less than or equal to that integer"""

    numbers = range( 3, highestNumber + 1, 2 ) 
    isPrime = [ True ] * len( numbers ) 
    primes = [2] if highestNumber >= 2 else []

    for number in numbers:
        if ( isPrime[(number-3)/2] ):
            increment = number
            position = (number * number - 3) / 2

            if ( position >= len( numbers )):
                primes += (x for x in numbers[(number-3)/2:] 
                             if isPrime[(x-3)/2])
                # primes += (2*i+3 for i in xrange((number-3)/2,
                #                   len(numbers)) if isPrime[i])
                break
            else:
                primes.append( number )
                while ( position < len( numbers )): 
                    isPrime[position] = False  
                    position += increment   
    return primes

Working on odds only is faster and takes less space. 仅在赔率上工作更快,并且占用空间更少。

We can start eliminating the multiples of n from n*n because for any n*k , k < n , we have n*k = k*n ie it will be eliminated as a multiple of k . 我们可以从n*n开始消除n的倍数,因为对于任何n*kk < n ,我们有n*k = k*n即它将被消除为k的倍数。

We can stop as soon as the square is above the top - all the multiples will have already been marked in the isPrime list, at this point. 只要正方形在顶部上方,我们就可以停止-此时,所有倍数都已经在isPrime列表中标记了。

The simplest method of computing the primes uses a sieve; 计算素数的最简单方法是使用筛子。 it was invented by the Greek mathematician Eratosthenes over two thousand years ago: 它是由希腊数学家Eratosthenes于2000年前发明的:

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

There are faster ways to compute the primes, but unless you know by measurement that your application requires greater speed than the function given above, or you haven't enough memory to store the sieve, you should use this method, which is simple and hard to get wrong. 有更快的方法来计算质数,但是除非通过测量得知应用程序需要比上述功能更快的速度,或者没有足够的内存来存储筛子,否则应使用此方法,该方法既简单又困难弄错了。 If you want to know more about the Sieve of Eratosthenes, I modestly recommend the essay Programming with Prime Numbers at my blog. 如果您想了解有关Eratosthenes筛网的更多信息,请在我的博客中谦虚地推荐“ 用质数编程 ”一文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM