How can I use the Sieve of Eratosthenes to get the nth prime?

后端 未结 1 1172
温柔的废话
温柔的废话 2021-01-13 05:14

I\'ve written a function, sieve(n), that uses the Sieve of Eratosthenes to return an array of all primes up to n.

sieve(25) # ==>         


        
1条回答
  •  终归单人心
    2021-01-13 05:42

    The sieve of Eratosthenes always has to start from the beginning; you can't sieve in some arbitrary interval since you'd loose all smaller primes. So you don't have to care for a lower bound, only for an upper bound. Which you gave, and which Wikipedia confirms:

    pn < n ln (n ln n) for n ≥ 6

    So simply take that bound, plug in your n and iterate till you have found n primes. Your sieve will usually be a bit too big, but not too much if the bound is reasonably tight, which I expect to be the case.

    See here for a table of that bound or here for a plot. By the way, the code creating the table is doing the same thing. I wanted at least 500 entries, so I computed

    n = 500
    lst = list(range(2, ceil(n*log(n*log(n)))))
    ps = []
    while lst:
        p = lst[0] # next prime
        ps.append(p)
        lst = [i for i in lst if i % p != 0]
    

    and got a bit over 500 primes out of it, for which I then could show you how the computed bound compares to the actual value.

    0 讨论(0)
提交回复
热议问题