简体   繁体   中英

There is a 4 in my prime number list generated in Python

Here is my code.

#Prime numbers between 0-100
for i in range(2,100):
    flg=0
    for j in range(2,int(i/2)):
        if i%j==0:
            flg=1
            break
    if flg!=1:
        print(i)

And the output is

2
3
4 <-
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97

I have no idea why there is this 4. Pardon me if i made some noobish mistake, as i can't seem to figure it out.

The reason is that range is not inclusive, ie

>>> range(2,2)
[]

So when you access 4, you don't check for divisors. Change for example to range(2,int(i/2)+1)

To speed up your calculation, you can use math.sqrt instead of /2 operation, for example as:

import math

and then

for j in range(2, int(math.sqrt(i)+1)):

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