Try... except....Try again?

Xavier Ho contact at xavierho.com
Fri Jul 17 11:50:14 EDT 2009


On Fri, Jul 17, 2009 at 11:02 PM, Jack Diederich <jackdied at gmail.com> wrote:

>
> If you use an off-the-shelf prime number generator fucntion[1] that
> returns consecutive primes the method collapses into a simple
> function.
>
> def nPrime(n, primes=[], next_prime=eratosthenes().next):
>    while len(primes) < n:
>        primes.append(next_prime())
>    return primes[n]
>
> -Jack
>
> [1]
> http://www.catonmat.net/blog/solving-google-treasure-hunt-prime-number-problem-four/#comment-3075
>     There is a deque implementation that is faster still but I can't
> find a link.


Jack, thanks for the link, I'll definitely look into it.

The function is currently implemented in a class I wrote myself, which is a
generator class that does exactly the same thing in the next() function. I
didn't post the code here because it wasn't in the scope of this thread, but
I'm sure others have done a lot better and much more efficient algorithms.

The nPrime method uses the nature of the iteration and checks if a value
already exists (ie generated before) and return that value; otherwise it
iterates again. This way, I don't have to iterate from n=2 and on every
time, which makes generation time linear.

However, I just gave the link's code a quick try. It was at least 10x times
faster than my code to generate 100000 prime numbers - I'll have a closer
look.

Thanks a great deal.

Ching-Yun "Xavier" Ho, Technical Artist

Contact Information
Mobile: (+61) 04 3335 4748
Skype ID: SpaXe85
Email: contact at xavierho.com
Website: http://xavierho.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090717/b6844c29/attachment-0001.html>


More information about the Python-list mailing list