寻找主要项目欧拉

Finding prime project euler

找到第 10,001 个质数。

我正在尝试在不使用我不理解的复制和粘贴代码的情况下解决 Project Euler 问题。 我编写了代码来判断一个数是否为质数,并试图将其修改为 运行 到前 10,001 个质数。我认为这会 运行 通过数字直到我休息,但它没有按预期工作。请记住,我已经尝试了其他几种方法来对此进行编码,而这是我认为可行的方法。我猜我把以前的东西弄得一团糟。

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)

您非常接近正确的解决方案。下次记得告诉我们您的期望和实际得到的结果。不要写类似

的东西

but it's not working as intended

以下是您必须进行的一些更改才能使其运行并更快!

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)

该代码用了 36.1 秒才找到 104743 作为第 10.001 个素数。