Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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+=1
    if counter == 0 or i == 2:
        counters+=1
    if counters == 10001:
        break
    else:
        pass
print(i)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
178 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 prime
    if 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 zero
    counter = 0
    for 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 time
            break;

    # you don't need to check the two here because 2%2 = 0, thus counter = 1    
    if counter == 0:
        counters+=1
    else:
        pass
    if counters == 10001:
        nth_prime = i
        break
print(nth_prime)

That code took me 36.1 seconds to find 104743 as the 10.001th prime number.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...