so this is a function that gets the nth prime number. I know its been done before and that my method may not be very efficient (new coder btw minor dabbling in the past). Anyway the code below works and returns the prime number of the supplied index. ie:
ind = 4
final[1,2,3,5,7,11]
return final[ind-1]
returns: 5
But final[51-1] returns whats in final[3-1]. Seems like after index 47 it loops back around and starts over. Ive printed the whole of the list contained in final. and it prints every prime, even those past 47. Im not sure whats going on. Is there some limit to lists in python?
Here is the code:
def nthPrime(ind): #gets nth prime number. IE: 5th prime == 11. works based off very in-efficient version of Sieve of Eratosthenes. but in increments of 200
p = {}
T = 2
incST = 2
incEND = incST + 200
final=[1]
while len(final) < ind:
for i in range(incST,incEND):
p[i] = True
while T <= math.sqrt(incEND):
l = 0
while l <= incEND:
p[T**2 + (T*l)] = False
l+=1
if T**2+(T*l) > incEND:
break
for k,v in p.items():
if p[k] == True and k > T:
T = int(k)
break
for k in p:
if p[k] == True:
final.append(k)
incST = incEND + 1
incEND = incST + 200
'''
currently function works perfectly for
any index under 48.
at index 48 and above it seems to start
back at index 1.
IE: final[51]
^would actually return final[4]
'''
return final[ind-1]
You need to count how many primes you have in your list, but you accumulate in
final
within the loop, so you add all the numbers up to the limit several times in the loop. Starts at 2 again after 199.Also, using dictionaries and relying on the order is dangerous. You should sort them when iterating.
My solution only counts the primes to know when to end the loop, and compose the list just in the end, omitting 1 and shifting the index by 1.
I also sort the dictionary when iterating over it to make sure: