我是一个尝试解决ProjectEuler问题的新手。
问题#10如下:求出两百万以下所有素数的和。
我的代码如下
a=1
s=0
p=[] #just wanna see the primes for myself so creating a list for that
while a<2000000: #while value of primes is less than 2million
if all(a%i!=0 for i in range(3,int(a**0.5)+1)): #checks if the number is prime
s=s+a #add primes to the sum
p.append(a) #add the primes to their list
a=a+2 #so that we only test odd numbers
print(s)
print(p)
所以问题是,数字1出现在列表中,而2没有出现。所有其他质数都包含在内。我尝试了许多调整,以找到10以下素数的总和和列表,但问题仍然存在。我做错了什么?
发布于 2016-04-08 23:41:11
您完全跳过了2,因为您在第一次迭代中从a=1
和a=a+2
开始
发布于 2016-04-08 23:43:34
从a=5开始,忽略前2个素数2和3。
和s=5(将前2个素数加起来,2和3)
从五百万到两百万。
A= a+2行将从a= 5开始。
https://stackoverflow.com/questions/36503739
复制相似问题