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).
import math
def main():
count = 3
one = 1
while one == 1:
for x in range(2, int(math.sqrt(count) + 1)):
if count % x == 0:
continue
if count % x != 0:
print count
count += 1
To test if a number is prime:
You can create a list of primes using list comprehensions in a fairly elegant manner. Taken from here:
Another simple example, with a simple optimization of only considering odd numbers. Everything done with lazy streams (python generators).
Usage: primes = list(create_prime_iterator(1, 30))
SymPy is a Python library for symbolic mathematics. It provides several functions to generate prime numbers.
Here are some examples.
Here is a numpy version of Sieve of Eratosthenes having both okay complexity (lower than sorting an array of length n) and vectorization.
Timings:
This seems homework-y, so I'll give a hint rather than a detailed explanation. Correct me if I've assumed wrong.
You're doing fine as far as bailing out when you see an even divisor.
But you're printing 'count' as soon as you see even one number that doesn't divide into it. 2, for instance, does not divide evenly into 9. But that doesn't make 9 a prime. You might want to keep going until you're sure no number in the range matches.
(as others have replied, a Sieve is a much more efficient way to go... just trying to help you understand why this specific code isn't doing what you want)