Finding The Nth Number Of Primes
Solution 1:
You need to change
root=int(sqrt(x))
into
root=int(sqrt(x))+1
(Take 9 for instance, int(sqrt(9))
is 3
, and range(3, 3, 2)
is []
, and you do really want to test dividing by 3
!).
Technically, 1 is not a prime either. Add
if(x<=1):
prime = False
and you'll get the same result as http://www.rsok.com/~jrm/first100primes.html
Solution 2:
Differently from what @Braxton says in a comment, the Sieve of Eratosthenes algorithm can easily be adapted to generate unbounded primes (e.g. as a potentially-infinite generator, which can then be curtailed as desired e.g. by itertools.slict
).
See this recipe for an unbounded Sieve in Python (and be sure to apply the enhancements shown in the comments, including mine;-) or see the same recipe as finally edited for the printed Cookbook here (unfortunately the discussion part is curtailed in this google books hit, but at least the Solution's code is all there;-).
Post a Comment for "Finding The Nth Number Of Primes"