简体   繁体   English

在Python中生成的素数列表中有4个

[英]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. 我不知道为什么有这个4.请原谅我,如果我犯了一些noobish错误,因为我似乎无法弄明白。

The reason is that range is not inclusive, ie 原因是范围不包括在内,即

>>> range(2,2)
[]

So when you access 4, you don't check for divisors. 所以当你访问4时,你不会检查除数。 Change for example to range(2,int(i/2)+1) 例如更改为range(2,int(i/2)+1)

To speed up your calculation, you can use math.sqrt instead of /2 operation, for example as: 要加快计算速度,可以使用math.sqrt而不是/ 2操作,例如:

import math

and then 接着

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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