Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

python - Finding prime project euler

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...