This is because you break the loop when len(k) == int(n)
and then access k[int(n)]
. Since python uses 0
based indexing, when the list length is equal to n
, the last index you can access is n-1
.
As you add 1 to the list, and 1 is not a prime, every other prime in the list will have their actual index.
I.e 2 is at index 1, and 2 is the first prime.
3 is at index 2, and 3 is the second prime.
So, the solution is to change len(k) == int(n)
to len(k) == int(n) + 1
.
NOTE: There is an another issue with your program. When ever the statements inside the outer loop get excuted. It keeps adding elements to k
unnecessarily. So, what i suggest is first calculate all the primes upto a certain limit. And then just query that list. Don't repeatedly calculate all the primes from the beginning.
k=[]
z=[]
a=0
k.append(1)
k.append(2)
k.append(3)
for x in xrange(3,7919,2):
for i in xrange(3,x,2):
if x%i!=0:
a=1
else:
a=0
break
if a==1:
k.append(x)
n = raw_input()
while n!="END" and int(n)>0 and int(n) < len(k):
print k[int(n)]
n = raw_input()