我要求创建一个名为primes(x)
的方法,该方法返回一个列表,其中包含从2开始一直到x的所有素数。
这是我的代码:
def primes(x):
i = 2
while(i < x):
j = 2
while(j <= (i/j)):
if not(i%j):
break
j = j + 1
if (j > i/j):
print(i, " is prime")
i = i + 1
预计将打印:
>>> primes(50)
(2, ' is prime')
(3, ' is prime')
(5, ' is prime')
(7, ' is prime')
(11, ' is prime')
(13, ' is prime')
(17, ' is prime')
(19, ' is prime')
(23, ' is prime')
(29, ' is prime')
(31, ' is prime')
(37, ' is prime')
(41, ' is prime')
(43, ' is prime')
(47, ' is prime')
然而,它没有打印2和3,它只打印:
(5, ' is prime')
(7, ' is prime')
(11, ' is prime')
(13, ' is prime')
(17, ' is prime')
(19, ' is prime')
(23, ' is prime')
(29, ' is prime')
(31, ' is prime')
(37, ' is prime')
(41, ' is prime')
(43, ' is prime')
(47, ' is prime')
答案 0 :(得分:2)
这是这一行:
while(j <= (i/j)):
当i为2或3时,j = 2
的起始值导致条件第一次评估为假。
答案 1 :(得分:0)
在while(j <= (i/j))
中,当i
为2或3时,while循环不会激活。
答案 2 :(得分:0)
了解
i = 2
while(i < x):
j = 2
while(j <= (i/j)):
由于j = 2
大于i/j
,因此i仅递增而不打印。 i = 3
也一样。
答案 3 :(得分:0)
如果问题是要打印2和3,那么这样就很容易了;)
def primes(x):
i = 2
print(2, " is prime")
print(3, " is prime")
while(i < x):
j = 2
while(j <= (i/j)):
if not(i%j):
break
j = j + 1
if (j > i/j):
print(i, " is prime")
i = i + 1