Project Euler #10 (Python)

前端 未结 9 1307
情深已故
情深已故 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条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-22 08:11

    First off, you're looping over too many numbers. You don't need to check if EVERY number less than a given number is a divisor to check if a number is prime (I'll let you figure out why this is yourself). You are running hundreds of billions of loops, where hundreds of millions will do.

    Something like this works faster, but is by no means optimal:

        value=2
        for i in range(3, 2000000):
            prime=True 
            if i%2 != 0:
                for j in range(3, int(round(sqrt(i)+1)),2):
                    if i % j==0:
                        prime=False
            else:
                prime=False
            if prime==True:
                value+=i
        print value
    

提交回复
热议问题