找到第10,001个素数。
我试图在不使用复制和粘贴我不理解的代码的情况下解决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)
答案 0 :(得分:0)
您非常接近正确的解决方案。请记住下次再告诉我们您究竟期望什么以及获得了什么。不要写类似的东西
但是它没有按预期工作
为了使它运行并使其更快,您必须进行一些更改!
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个素数。