本题来自 Project Euler 第10题:https://projecteuler.net/problem=10
# Project Euler: Problem 10: Summation of primes
# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
# Find the sum of all the primes below two million.
# Answer: 142913828922
def f(x): #判断 x 是否为素数,返回bool值
if x == 2:
return True
elif x <= 1:
return False
else:
t = False #判断是否能够整除
for i in range(2, int(x**.5)+1):
if x%i == 0:
t = True
break
if t: #若能整除
return False
else:
return True
sum = 0
for i in range(1, 2000000):
if f(i):
sum += i
print(sum)
又是一道求解素数的题目。看来,只要能找到判断素数的最佳方法,就能解决很多问题啊。
本题沿用了之前的素数判断函数。不知道有没有优化的版本,能大幅压缩计算时间啊……