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
For me, the below solution looks simple and easy to follow.
We will get all the prime numbers upto 20 in a list. I could have used Sieve of Eratosthenes but you said you want something very simple. ;)
If you wanted to find all the primes in a range you could do this:
Just add
while its <=
and your number for the range.OUTPUT:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101
There are some problems:
continue
moves to the next loop iteration - but you really want to stop it usingbreak
Here's your code with a few fixes, it prints out only primes:
For much more efficient prime generation, see the Sieve of Erastothenes, as others have suggested. Here's a nice, optimized implementation with many comments:
Note that it returns a generator.