素数查找器,包括2个多次

2024-04-27 03:48:26 发布

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

这个程序使所有素数的列表小于或等于给定的输入。你知道吗

然后打印列表。你知道吗

我不明白为什么它包括数字2。当我第一次设计这个程序时,我用primes=[2]初始化了这个列表,因为我想,既然2%2==0

if n % x == 0:
    is_prime = False

is_prime设置为False。然而,情况似乎并非如此。你知道吗

我确信我的range()for循环中的逻辑发生了一些我不明白的事情。你知道吗

我想我的问题是:为什么每次2都会出现在素数列表中?你知道吗

import math


limit = int(input("Enter a positive integer greater than 1: "))

while limit < 2:
    limit = int(input("Error.  Please enter a positive integer greater than 1: "))

primes = []

#Check all numbers n <= limit for primeness
for n in range (2, limit + 1):
    square_root = int(math.sqrt(n))
    is_prime = True

    for x in range(2, (square_root + 1)):
        if n % x == 0:
            is_prime = False

    if is_prime:
        primes.append(n)

#print all the primes
print("The primes less than or equal to", limit, "are:")
for num in primes:
    print(num)

Tags: in程序false列表forifisrange
1条回答
网友
1楼 · 发布于 2024-04-27 03:48:26

因为在测试n=2时没有进入第二个for-循环,因此没有设置is_prime = False。你知道吗

# Simplified test case:
x = 2
for idx in range(2, int(math.sqrt(x))+1): 
    print(idx)

这不print任何东西,因为range在本例中是:range(2, 2),因此长度为零。你知道吗


请注意,您的方法并非真正有效,因为:

  • 你用所有可能的除数测试每个数,即使你已经发现它不是素数。你知道吗
  • 在测试中不排除素数的倍数:如果2是素数,那么2的每一个倍数都不能是素数,以此类推

查找Fastest way to list all primes below N中提到的素数有很多很好的函数,所以我就不赘述了。但是如果你对改进感兴趣的话,你可能想看看。你知道吗

相关问题 更多 >