0
def is_prime(x):
    if x<2:
        return False
    elif x%2==0:
        if x==2:
            return True
        else:
            return False
    else:
        for i in range(3,x+1,2):
            if x%i==0 and i==x:
                return True
                break
            elif x%i==0:
                return False
                break


def sum_primes(m):
    total=0
    for i in range (3,m,2):
        if is_prime(i):
            total+=i
    return total+2

print sum_primes(2000000)

I'm trying to solve one the Project-Euler problems, and this program works but it takes too much time to give me the answer. How can I make it faster guys ?

Martijn Pieters
  • 889,049
  • 245
  • 3,507
  • 2,997
Thoperno
  • 1
  • 1
  • 1
    have a look at the [Sieve of Erathostenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes). You can find some Python implementations [here](http://rosettacode.org/wiki/Sieve_of_Eratosthenes#Python) – Cristian Lupascu Dec 30 '13 at 21:16
  • 1
    If you're asking how to improve your specific code, take it to [Code Review](http://codereview.stackexchange.com). If you're asking for a faster algorithm, that's been asked hundreds of times, which is why the Related questions sidebar is full of obvious duplicates. – abarnert Dec 30 '13 at 21:35

2 Answers2

2

This question has been asked before:

There are multiple approaches listed in the above links. You might also find this link helpful:

You might also consider trying to optimize this using Cython.

Community
  • 1
  • 1
Mike Driscoll
  • 31,394
  • 6
  • 39
  • 83
0

The Sieve of Eratosthenes enumerates the primes, sum accumulates them; first make a list of the number from 2 to n, marking them prime, then scan the list in order, stopping at each prime to mark its multiples composite, collecting the primes in order.

function sumPrimes(n) # sum of primes less than n
    sum, sieve := 0, makeArray(2..n, True)
    for p from 2 to n
        if sieve[p]
            sum := sum + p
            for i from p*p to n step p
                sieve[i] = False
    return sum

I'll leave it to you to translate to Python.

If you're interested in programming with prime numbers, I modestly recommend this essay at my blog.

user448810
  • 16,364
  • 2
  • 31
  • 53