You are pretty close to the right solution. Remember next time to tell us what exactly you expected and what you got instead. Don't write something like
but it's not working as intended
Here are some changes you have to make to make it work and to make it faster !
import math
import itertools
counter = 0
counters = 0
nth_prime = 0
for i in itertools.count():
# ignore numbers smaller than 2 because they are not prime
if i < 2:
continue
# The most important change: if you don't reset your counter to zero, all but the first prime number will be counted as not prime because your counter is always greater than zero
counter = 0
for n in range (2, math.ceil(i/2)+1):
if i%n == 0:
counter = 1
# if you find out your number is not prime, break the loop to save calculation time
break;
# you don't need to check the two here because 2%2 = 0, thus counter = 1
if counter == 0:
counters+=1
else:
pass
if counters == 10001:
nth_prime = i
break
print(nth_prime)
That code took me 36.1 seconds to find 104743 as the 10.001th prime number.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…