Reputation: 1227
I've written a simple primes list generator for range(3 - 2000). For some reason, the code prints out a bunch of duplicates, and I have no idea why. This is my primes generator:
import math
def printprimes():
count = 3
Lessthan2000 = True
while Lessthan2000 == True:
for x in range(2, int(math.sqrt(count)) + 1):
if count % x == 0:
break
else:
print count
if count >= 2000:
Lessthan2000 = False
count += 1
The resulting printout includes stretches like this:
1993
1993
1993
1993
1995
1997
1997
1997
1997
1997
1997
What's going on here? Thanks in advance!
Upvotes: 0
Views: 83
Reputation: 43507
With better names, proper iteration, and a docstring, determining why there are duplicates is easy because there are none.
import math
def print_primes(limit):
"""Prints all prime numbers from 3 to limit inclusive.
This uses a simple algorithm which tests
each candidate for possible factors.
"""
for current in range(3, limit + 1):
for candidate in range(2, int(math.sqrt(current)) + 1):
if current % candidate == 0:
break # current has a factor other than itself
else:
print(current)
print_primes(2000)
Upvotes: 1
Reputation: 1372
else
clause should belong to for
instead of if
for x in range(2, int(math.sqrt(count)) + 1):
if count % x == 0:
break
else:
print count
which means print count
if for
ends without a break
.
Upvotes: 3