-1

I wrote this simple python function to calc:

def isPrime(number):
    if number == 2:
        return True

    elif number > 1 and number % 2 != 0:
        for current in range(3, number):
            if number % current == 0:
                return False

        return True

And I'm calling it to print out the sum of all prime numbers from 1 to 2 million, as in project euler #10

However it's terribly slow, and I was wondering if I could tackle the same problem using generators? But I don't really understand generators in python completely..

Any help on how to solve this problem more efficiently would be appreciated! Thanks :)

wnnmaw
  • 4,906
  • 2
  • 31
  • 60
  • Why do you check every number? – Peter Wood Mar 21 '16 at 17:59
  • 2
    Complete and functioning blocks of code which are looking to be improved can be directed at the [Code Review Stack Exchange](http://codereview.stackexchange.com/). Be sure to review that site's help center before posting – wnnmaw Mar 21 '16 at 17:59

2 Answers2

0

Firstly, I suggest you use a better function to check whether a number is prime or not. Here's a better modification, from https://jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/ which is an excellent explanation on generators in Python.

import math

def is_prime(number):
    while True:
        if number == 2:
            return True
        elif number > 1 and number % 2 != 0:
            for current in range(3, int(math.sqrt(number) + 1), 2):
                if number % current == 0:
                    return False
            return True
        return False

Secondly, you need to understand what a Generator actually does. Again Jeff Knupp explains it perfectly. In short a generator is a function that does not "return" it simply "yields" and takes back control when the next() method is called on it. So no variables that are created during the function are lost, and memory is saved by not creating the variables defined in the function again and again.

Then you can go on solving Euler 10, which is also explained in the link. :)

Good luck with the rest of the Eulers!

ShadowRanger
  • 108,619
  • 9
  • 124
  • 184
SinByCos
  • 533
  • 1
  • 6
  • 18
0

Another angle of attack on this problem is to try a different algorithm rather than attempting to optimize your current method. Learning more about generators is great, but you could also try solving this using a sieve, which can be quite efficient.

The general idea would be to "mark" all composite numbers (not prime), leaving behind the primes. It's pretty efficient, as my python implementation runs in ~3.5s

Count Zero
  • 146
  • 1
  • 5