Find the 10,001st prime number.
I am trying to do Project Euler problems without using copying and pasting code I don't understand.
I wrote code that finds whether a number is prime or not and am trying to modify it to run through the first 10,001 primes. I thought that this would run through numbers until my break, but it's not working as intended. Bear in mind I have tried a few other ways to code this and this was the one I thought could work. I am guessing that I somewhat made a mess of what I had before.
import math
import itertools
counter = 0
counters = 0
for i in itertools.count():for n in range (2, math.ceil(i/2)+1):if i%n == 0:counter+=1if counter == 0 or i == 2:counters+=1if counters == 10001:breakelse:pass
print(i)
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 primeif 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 zerocounter = 0for 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 timebreak;# you don't need to check the two here because 2%2 = 0, thus counter = 1 if counter == 0:counters+=1else:passif counters == 10001:nth_prime = ibreak
print(nth_prime)
That code took me 36.1 seconds to find 104743 as the 10.001th prime number.