I'm working on a program which will found the n
th. prime number. For example, By listing the first six prime numbers: 2, 3, 5, 7, 11
and 13
, we can see that the 6th prime is 13
. I'm trying to making an algorithm, like, if I want to see 50th prime, I will add 1
to ends of the range()
function. I'm using this algorithm to find primes at the moment;
cnt = 1
print (2)
for x in range(3,40,2):
div = False
for y in range(2,round(x**0.5)+1):
if x%y == 0:
div = True
if div == False:
print (x)
cnt += 1
print ("\nThere is {} prime numbers.".format(cnt))
You see that, I put 40
. But I want to put n
there, so for example, untill reaching the 50th prime, add +1 to n
. But it's not going to like that, if I tried something like;
cnt = 1
n = 40 #example
while cnt<50:
for x in range(3,n,2):
#codes
if div == False:
n += 1
I thought when the program finds a prime, it will add +1 to n
and while
loop will process untill find the 50th prime. But it didn't, primes are wrong if I use this one also, nothing relevant what I want to do.
How to make this algorithm, obviously changing the last element of
range()
function does not working.Is there better/elegant algorithm/way? If I want to find
200.000th
prime, I need faster codes.
Edit: I was working with lists first but, I got MemoryError all the time when working with big numbers. So I pass that and using a variable that counting how much primes are there cnt
.