简体   繁体   English

查找1至20代码之间的质数而不返回质数2,什么是正确的算法?

[英]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=2j=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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM