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