简体   繁体   中英

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

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

You misplaced the else , which makes the sieve dysfunctional. In addition the inner loop should only iterate until 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 . With the corrected code, i will only be appended, if the inner loop isn't terminated by a break . 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.

In the first iteration of the two loops - i=2 and j=2 . The if condition is then true and therefore the inner loop stops without adding 2 to a .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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