Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out 20th, 30th, nth prime number. (I'm getting 20th but not 30th?) [Python]

Tags:

python

primes

The question is to find the 1000th prime number. I wrote the following python code for this. The problem is, I get the right answer for the 10th , 20th prime but after that each increment of 10 leaves me one off the mark. I can't catch the bug here :(

count=1            #to keep count of prime numbers
primes=()          #tuple to hold primes
candidate=3        #variable to test for primes
while count<20:
    for x in range(2,candidate):
        if candidate%x==0:
            candidate=candidate+2
        else : pass
    primes=primes+(candidate,)            
    candidate=candidate+2
    count=count+1
print primes        
print "20th prime is ", primes[-1]

In case you're wondering, count is initialised as 1 because I am not testing for 2 as a prime number(I'm starting from 3) and candidate is being incremented by 2 because only odd numbers can be prime numbers. I know there are other ways of solving this problem, such as the prime number theorem but I wanna know what's wrong with this approach. Also if there are any optimisations you have in mind, please suggest.

Thank You

like image 234
gsin Avatar asked Jan 03 '10 18:01

gsin


People also ask

What are the prime numbers between 20 and 30 *?

23 and 29 are the prime numbers between 20 and 30.

How do you check a number is prime or not in Python?

Check if a number is Prime or not using sqrt()from math import sqrt # Number to be checked for prime n = 9 flag = 0 if(n > 1): for k in range(2, int(sqrt(n)) + 1): if (n % k == 0): flag = 1 break if (flag == 0): print(n," is a Prime Number! ") else: print(n," is Not a Prime Number!

How do you find the nth prime number?

An easy way to determine if a number is prime is by trial division: divide the number n by all the integers less than n, and if no exact divisors–other than 1–are found, then n is prime. You can see how this becomes time-consuming as the value of n increases.


1 Answers

There is a nice Sieve of Eratosthenes generator implementation in test_generators.py:

def intsfrom(i):
     while 1:
         yield i
         i += 1

def firstn(g, n):
     return [g.next() for i in range(n)]

def exclude_multiples(n, ints):
     for i in ints:
         if i % n:
             yield i    

def sieve(ints):
     prime = ints.next()
     yield prime
     not_divisible_by_prime = exclude_multiples(prime, ints)
     for p in sieve(not_divisible_by_prime):
         yield p

primes = sieve(intsfrom(2))

>>> print firstn(primes, 20)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]

alt text

like image 150
jbochi Avatar answered Sep 18 '22 16:09

jbochi