Project Euler #10 (Python)

前端 未结 9 1299
情深已故
情深已故 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:06
    sum = 2
    
    def isPrime(n):
        if n % 2 == 0: return False
        for i in range(3, int(n**0.5)+1, 2):
            if n % i == 0: return False
        return True
    if __name__ == "__main__":
        n = 1
        while n < 2000000:
            n += 2
            if isPrime(n):sum += n
    print sum
    
    0 讨论(0)
  • 2021-01-22 08:08

    There are many optimisations that you could do (and should do since you will need prime generation for many of the problems in project Euler, so having a fast implementation simplifies things later on).

    Take a look at the sieve of Atkin (and related sieves) (http://en.wikipedia.org/wiki/Sieve_of_Atkin) to get an understanding of how prime generation can be speeded up over brute force (algorithmically that is).

    Then take a look at the awesome answer to this S.O.-post (Fastest way to list all primes below N) that clocks a number of prime generation algorithms/implementations.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题