for each in range(2,501):
n=0
for i in range(2,each):
if each%i !=0:
n+=1
if n==each-2:
sum = sum+each
print(sum)
本帖最后由 sunrise085 于 2021-1-27 21:07 编辑
你的程序31行有问题,永远为真,导致所有的循环都经过这个if,导致最终结果为0
直接修改你的程序如下:
sum = 0
for each in range(2,500):#从2开始,1不是质数
if each in(2,3,5,7,11,13,17,19,23):#这个应该放在前面,应该这样写。
sum+=each
elif each % 2 == 0:
pass
elif each % 3 == 0:
pass
elif each % 5 == 0:
pass
elif each % 7 == 0:
pass
elif each % 11 == 0:
pass
elif each % 13 == 0:
pass
elif each % 17 == 0:
pass
elif each % 19 == 0:
pass
elif each % 23 == 0:
pass
else:
sum = sum+each
print(sum)
你的程序只针对500有效,如果是一个很大的数,那么if需要把所有的质数都写一遍,这就不是写程序的初衷了。
正确程序如下:
sum=0
for n in range(2,500):
for j in range(2,n):
if n%j == 0:
break
else:
sum+=n
print(sum) sum = 0
for each in range(1,500):
if each == 1:
pass
elif each > 2 and each % 2 == 0:
pass
elif each > 3 and each % 3 == 0:
pass
elif each > 5 and each % 5 == 0:
pass
elif each > 7 and each % 7 == 0:
pass
elif each > 11 and each % 11 == 0:
pass
elif each > 13 and each % 13 == 0:
pass
elif each > 17 and each % 17 == 0:
pass
elif each > 19 and each % 19 == 0:
pass
elif each > 23 and each % 23 == 0:
pass
else:
sum += each
print(sum) 本帖最后由 qq1151985918 于 2021-1-28 00:34 编辑
num = 500
primeNumList = []
for i in range(2 ,num + 1):
for j in range(2 ,i//2 + 1):
if i % j == 0:
break
else:
primeNumList.append(i)
print(primeNumList)
print(sum(primeNumList))
页:
[1]