我可以理解如何在3之后添加其他质数,因为(x%y != 0),但对于for循环的第一次迭代,x%y似乎等于0。那么,它怎么会被添加到我的主要列表中呢?
def count_primes(num):
# edge case: 1 and 0 are not prime numbers
if num < 2:
return 0
# create prime list, check length to find amount of primes up to input num
# insert 2 bc it is only even prime number. Allows use of step in range to only iterate odds
primes = [2]
# create variable that holds prime candidates starting after 2
x = 3
# proceed into loop if prime candidate is less than or equal to input number
while x <= num:
# cycle through odd numbers up to input number
for y in range(3,x,2):
if x%y == 0:
x += 2
break
else:
primes.append(x)
x += 2
return primes发布于 2020-01-14 06:26:19
当
x为3时,range(3,x,2)是一个空范围-因此不会对该数字执行%测试。
https://stackoverflow.com/questions/59724962
复制相似问题