Program to compute and print 1000th prime number
John Posner
jjposner at optimum.net
Sat Nov 7 13:18:18 EST 2009
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/>
More information about the Python-list
mailing list