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
Here is what I have:
It's pretty fast for large numbers, as it only checks against already prime numbers for divisors of a number.
Now if you want to generate a list of primes, you can do:
using generators here might be desired for efficiency.
And just for reference, instead of saying:
you can simply say:
You need to make sure that all possible divisors don't evenly divide the number you're checking. In this case you'll print the number you're checking any time just one of the possible divisors doesn't evenly divide the number.
Also you don't want to use a continue statement because a continue will just cause it to check the next possible divisor when you've already found out that the number is not a prime.
To my opinion it is always best to take the functional approach,
So I create a function first to find out if the number is prime or not then use it in loop or other place as necessary.
Then run a simple list comprehension or generator expression to get your list of prime,
The continue statement looks wrong.
You want to start at 2 because 2 is the first prime number.
You can write "while True:" to get an infinite loop.
Similar to user107745, but using 'all' instead of double negation (a little bit more readable, but I think same performance):
Basically it iterates over the x in range of (2, 100) and picking only those that do not have mod == 0 for all t in range(2,x)
Another way is probably just populating the prime numbers as we go: