我对算法非常陌生,不久前才开始编写代码。请用this problem from Project Euler帮助我:
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
我试着阅读了关于Sieve算法的知识,并在理解了这个概念之后实现了它。你知道吗
def SieveofEratosthenes(n):
prime = [True for i in range(n+1)]
p = 2
while(p*p <= n):
if(prime[p] == True):
for i in range(p*p, n+1, p):
prime[i] = False
p+=1
for p in range(2, n):
if prime[p]:
print(p),
#Driver Program
if __name__=='__main__':
n=2000000
print('Following are the prime numbers smaller than or equal to', n)
SieveofEratosthenes(n)
问题是时间太长了。在我的机器上花了7.8秒。 加上我怎么把这些数字加起来?有什么更好的方法处理它?你知道吗
以下是您的答案:
它提示:
一些评论
if foo == True
可以像if foo
一样编写相关问题 更多 >
编程相关推荐