[英]finding prime numbers between 1 to 20 code not returning prime number 2,what is the correct algorithm?
Finding prime numbers between 1 to 20 查找1至20之间的质数
a = []
for i in range(2,20):
for j in range(2,20):
if((i % j) == 0):
break;
else:
a.append(i)
return a
This is the output I got - 这是我得到的输出-
[3, 5, 5, 5, 7, 7, 7, 7, 7, 9, 11, 11, 11, 11, 11, 11, 11, 11, 11, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 15, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19]
I expect 2 should also be included in the output 我希望2也应该包含在输出中
You misplaced the else
, which makes the sieve dysfunctional. 您放错了
else
,这使筛子无法正常工作。 In addition the inner loop should only iterate until j == i - 1
. 另外,内部循环只应迭代直到
j == i - 1
为止。 The correct code would look like this: 正确的代码如下所示:
a = []
for i in range(2,20):
for j in range(2,i):
if((i % j) == 0):
break
else:
a.append(i)
return a
The difference: in the original code any i
for which a j
is found, such that i % j != 0
, will be appended to a
. 差:在原始代码中的任何
i
针对其j
被发现,使得i % j != 0
将被附加到a
。 With the corrected code, i
will only be appended, if the inner loop isn't terminated by a break
. 使用更正后的代码,如果内部循环没有被
break
终止,则只会附加i
。 Also your code tests for divisibility for all numbers in the range [2, 20[
, but even primes are divisible by themselves, which is why 2 wasn't part of the output of your code. 另外,您的代码还会测试[2,20
[2, 20[
范围内所有数字的可除性,但即使素数也可被自身整除,这就是为什么2不在代码输出中的原因。
In the first iteration of the two loops - i=2
and j=2
. 在两个循环的第一次迭代中
i=2
和j=2
。 The if condition is then true and therefore the inner loop stops without adding 2 to a
. 如果条件是真,然后,因此,内循环停止而不增加2至
a
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.