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
x
14
14
1
import math
2
3
def main():
4
count = 3
5
one = 1
6
while one == 1:
7
for x in range(2, int(math.sqrt(count) + 1)):
8
if count % x == 0:
9
continue
10
if count % x != 0:
11
print count
12
13
count += 1
14
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 usingbreak
Here’s your code with a few fixes, it prints out only primes:
JavaScript
1
18
18
1
import math
2
3
def main():
4
count = 3
5
6
while True:
7
isprime = True
8
9
for x in range(2, int(math.sqrt(count) + 1)):
10
if count % x == 0:
11
isprime = False
12
break
13
14
if isprime:
15
print count
16
17
count += 1
18
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
1
38
38
1
# Sieve of Eratosthenes
2
# Code by David Eppstein, UC Irvine, 28 Feb 2002
3
# http://code.activestate.com/recipes/117119/
4
5
def gen_primes():
6
""" Generate an infinite sequence of prime numbers.
7
"""
8
# Maps composites to primes witnessing their compositeness.
9
# This is memory efficient, as the sieve is not "run forward"
10
# indefinitely, but only as long as required by the current
11
# number being tested.
12
#
13
D = {}
14
15
# The running integer that's checked for primeness
16
q = 2
17
18
while True:
19
if q not in D:
20
# q is a new prime.
21
# Yield it and mark its first multiple that isn't
22
# already marked in previous iterations
23
#
24
yield q
25
D[q * q] = [q]
26
else:
27
# q is composite. D[q] is the list of primes that
28
# divide it. Since we've reached q, we no longer
29
# need it in the map, but we'll mark the next
30
# multiples of its witnesses to prepare for larger
31
# numbers
32
#
33
for p in D[q]:
34
D.setdefault(p + q, []).append(p)
35
del D[q]
36
37
q += 1
38
Note that it returns a generator.