Finding first n primes? [duplicate]

筅森魡賤 提交于 2019-12-06 12:35:22

问题


Possible Duplicate:
Fastest way to list all primes below N in python

Although I already have written a function to find all primes under n (primes(10) -> [2, 3, 5, 7]), I am struggling to find a quick way to find the first n primes. What is the fastest way to do this?


回答1:


Start with the estimate g(n) = n log n + n log log n*, which estimates the size of the nth prime for n > 5.

Then run a sieve on that estimate. g(n) gives an overestimate, which is okay because we can simply discard the extra primes generated which are larger than the desired n.

Then consider the answers in "Fastest way to list all primes below N in python".

If you are concerned about the actual runtime of the code (instead of the order of magnitude of the time complexity of the algorithm), consider using one of the solutions that use numpy (instead of one of the "pure python" solutions).

*When I write log I mean the natural logarithm.




回答2:


According to this, the nth prime number p_n satisfies

p_n < n ln(n) + n ln( ln(n) )

for n >= 6

So if you run your current function (or, e.g., one of the sieves mentioned in other answers) using the next integer greater than the right-hand side above, you are guaranteed to find the nth prime.




回答3:


You want the Sieve of Eratosthenes.

Use the π function to estimate what value of n you want to look towards, overshoot slightly, and then use a sieve to compute up to the point you need.




回答4:


Use sieve of Erastothrones using the fact that prime numbers are either of the form 6n+1 or 6n-1 after 2 and 3.This will improve the speed of the program




回答5:


I don't know if it's the fastest but Euler's Sieve seems good.

EDIT

As the other answers is suggesting you can use basic facts on the prime number theorem2. Or you can learn basic algebraic geometry and use elliptic curve primality testing.



来源:https://stackoverflow.com/questions/4911777/finding-first-n-primes

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