Finding prime project euler

依然范特西╮ 提交于 2019-12-13 08:55:37

问题


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)

回答1:


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.



来源:https://stackoverflow.com/questions/56422865/finding-prime-project-euler

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!