Skip to content
Advertisement

Simple prime number generator in Python

Could someone please tell me what I’m doing wrong with this code? It is just printing ‘count’ anyway. I just want a very simple prime generator (nothing fancy).

JavaScript

Advertisement

Answer

There are some problems:

  • Why do you print out count when it didn’t divide by x? It doesn’t mean it’s prime, it means only that this particular x doesn’t divide it
  • continue moves to the next loop iteration – but you really want to stop it using break

Here’s your code with a few fixes, it prints out only primes:

JavaScript

For much more efficient prime generation, see the Sieve of Eratosthenes, as others have suggested. Here’s a nice, optimized implementation with many comments:

JavaScript

Note that it returns a generator.

Advertisement