ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> python-list
python-list
Re: Program to compute and print 1000th prime number
by John Posner other posts by this author
Nov 7 2009 10:22AM messages near this date
Re: Program to compute and print 1000th prime number | Re: Program to compute and print 1000th prime number
Robert P. J. Day said:
>    the ubiquitous sieve of eratosthenes requires you to pre-specify
>  your maximum value, after which -- once the sieve completes -- all you
>  know is that you have all of the prime numbers up to n.  whether
>  you'll have 1000 of them isn't clear, which means that you might have
>  to start all over with a larger maximum value.  (being able to
>  directly determine the n'th prime number would solve a *lot* of prime
>  number problems. :-)
> 
>    
In April of this year, members of this forum helped me to devise a 
prime-number iterator [1]. So here's a simple solution for the OP:

#---------------
from itertools import ifilter, count

# create iterator
prime_iter = ifilter(
    lambda n, P=[]: all(n%p for p in P) and not P.append(n),
                    count(2))

# throw away lots of primes
for i in range(999):   
    prime_iter.next()
   
# here's the one we want
print prime_iter.next()      #7919
#---------------

I don't think this is a solution that a course instructor would expect, 
though!

As mentioned in [1], optimizations of this algorithm (using 
itertools.takewhile() and/or caching previously-computed squares) are 
still at cl1p.net [2].

-John

[1]  http://mail.python.org/pipermail/python-list/2009-April/177415.html

[2]  http://www.cl1p.net/python_prime_generators


 <http://cl1p.net/python_prime_generators/> 



-- 
http://mail.python.org/mailman/listinfo/python-list
Thread:
Ray Holt
Xavier Ho
Wayne Brehaut
John Posner
Mensanator
Andre Engels
ssteinerX@gmail.com
Raymond Hettinger
Robert P. J. Day
Robert P. J. Day

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState Software Inc. All rights reserved