这个程序使所有素数的列表小于或等于给定的输入。你知道吗
然后打印列表。你知道吗
我不明白为什么它包括数字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)
因为在测试
n=2
时没有进入第二个for
-循环,因此没有设置is_prime = False
。你知道吗这不
print
任何东西,因为range
在本例中是:range(2, 2)
,因此长度为零。你知道吗请注意,您的方法并非真正有效,因为:
查找Fastest way to list all primes below N中提到的素数有很多很好的函数,所以我就不赘述了。但是如果你对改进感兴趣的话,你可能想看看。你知道吗
相关问题 更多 >
编程相关推荐