为什么我的素数生成器返回重复的?

2024-04-24 18:45:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经为range(3-2000)编写了一个简单的素数列表生成器。出于某种原因,代码打印出一堆副本,我不知道为什么。这是我的素数发生器:

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

生成的打印输出包括如下拉伸:

1993
1993
1993
1993
1995
1997
1997
1997
1997
1997
1997

这是怎么回事?提前谢谢!你知道吗


Tags: 代码importtrue列表forifdefcount
2条回答

else子句应该属于for,而不是if

for x in range(2, int(math.sqrt(count)) + 1):
    if count % x == 0:
        break
else:
    print count

也就是说print count如果for结束时没有break。你知道吗

使用更好的名称、适当的迭代和docstring,很容易确定为什么会有重复项,因为没有重复项。你知道吗

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)

相关问题 更多 >