简体   繁体   中英

Why does my primes generator return duplicates?

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!

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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM