Prime numbers generator explanation? [duplicate]

柔情痞子 提交于 2019-12-01 16:54:28

问题


I was searching for an algorithm to generate prime numbers. I found the following one done by Robert William Hanks. It is very efficient and better than the other algorithms but I can not understand the math behind it.

def primes(n):
    """ Returns  a list of primes < n """
    lis = [True] * n
    for i in range(3,int(n**0.5)+1,2):
        if lis[i]:
            lis[i*i::2*i]=[False]*int((n-i*i-1)/(2*i)+1)
    return [2] + [i for i in range(3,n,2) if lis[i]]

What is the relation between the array of Trues values and the final prime numbers array?


回答1:


Starting with n True values in an array, with i enumerated from 3 to sqrt(n) by step of 2, if ith entry in the array is still True, set all entries from i^2 to the end of the array by step of 2*i to False (these will be the multiples of i).

All odd True entries that are left in the array in the end, are prime.

All thus found numbers, and 2, are all the prime numbers that exist below n.



来源:https://stackoverflow.com/questions/42811019/prime-numbers-generator-explanation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!