Project Euler #10 (Python)

前端 未结 9 1313
情深已故
情深已故 2021-01-22 07:27

Why is my algorithm for finding the sum of all prime numbers below 2 million so slow? I\'m a fairly beginner programmer and this is what I came up with for finding the solution:

9条回答
  •  旧时难觅i
    2021-01-22 07:55

    import time
    start = time.time()
    
    def is_prime(num):
        prime = True
        for i in range(2,int(num**0.5)+1):
            if num % i == 0:
                prime = False
                break
        return prime
    sum_prime = 0
    for i in range(2,2000000):
        if is_prime(i):
            sum_prime += i
    print("sum: ",sum_prime)
    
    elapsed = (time.time() - start)
    print("This code took: " + str(elapsed) + " seconds")
    

提交回复
热议问题