1

I'm fairly new to Python, and am trying to practice programming by doing Project Euler problems. In order to solve the 7th problem, I decided to first build a simple prime generating function using for loops, which doesn't seem to work.

Here's my code:

primes = [2]

for n in range(2, 10):
    for m in range(2, n):
        if not(n % m):
            primes.append(n)

print primes

The output is [2,4,6,6,8,8,9] instead of what I intended, i.e. [2,3,5,7]. The math seems correct to me: Pick a natural number, n, bigger than two. For all natural numbers m bigger than one, but smaller than n, check if n is divisible by m. If not, add n to the list of primes. Can anyone please tell me what's wrong with my code?

P.S. While I know there are several other (and better) ways of generating primes, I am interested in making my approach (code) work.

Community
  • 1
  • 1

1 Answers1

3

not(n % m) tells you if a number is not prime.

You also need to do it for every candidate factor before you know if the number is prime or not.

Python has a very handy mechanism for this in for: else:, which only runs the else block if you did not break from the for.

primes = []
for n in range(2, 10):
    for m in range(2, n):
        if not(n % m):
            break
    else:
        primes.append(n)

You can test primality in a similar way with a generator expression:

prime = not(any(n % m == 0 for m in range(2, n)))

Remember range is inefficient in Python 2.x, as it generates the entire list of numbers before starting iteration. Use xrange unless you're on Python 3.x

lunixbochs
  • 21,757
  • 2
  • 39
  • 47
  • I added the break and else statements, according to your suggestion, and got [2, 3, 5, 5, 5, 7, 7, 7, 7, 7, 9] as an output. Do you know why it returns 5 and 7 multiple times? – chubbycantorset Dec 05 '14 at 07:59
  • Did you put the else at the wrong depth? That's not the output I get when running the exact code I submitted. – lunixbochs Dec 05 '14 at 08:01
  • Yes, that was my mistake. I incorrectly assumed that the else statement should be on the same depth as the if statement. Thanks again! – chubbycantorset Dec 05 '14 at 08:03