Hello,
This is driving me crazy so here it goes.
I'm trying to create a program that finds the 1000th prime number. This is the code I started with to check if a number is prime:
numberofprimesfound = 0
numbertotest = 303
divisor = 2
if numbertotest%divisor == 0:
print numbertotest, 'Is not a prime (broke at stage 1)'
else:
while divisor < numbertotest:
divisor = divisor +1
if numbertotest%divisor == 0:
print numbertotest, 'Is not a prime (broke at stage 2)'
numbertotest = numbertotest +2
break
elif numbertotest%divisor <> 0:
print numbertotest, 'Is a prime'
numbertotest = numbertotest +2
numberofprimesfound = numberofprimesfound +1
break
This works correctly to check if any number is a prime above 3.
However when I add a while loop to find the 1000th prime it all goes wrong.
numberofprimesfound = 0
numbertotest = 5
divisor = 2
while numberofprimesfound < 1000:
if numbertotest%divisor == 0:
numbertotest = numbertotest +2
divisor = 2
else:
while divisor < numbertotest:
divisor = divisor +1
if numbertotest%divisor == 0:
numbertotest = numbertotest +2
divisor = 2
break
elif numbertotest%divisor <> 0:
numbertotest = numbertotest +2
numberofprimesfound = numberofprimesfound +1
divisor = 2
break
print 'The', numberofprimesfound,'th prime is', numbertotest
The loop reports the 1000th prime to be 3003 which obviously isnt right. But I cant figure out why when the prime check works fine it all breaks when I simply add a while loop.
Any ideas?
Thanks