我为Python素数生成器编写了代码,以生成前100个素数.但是,不知何故,我在输出中得到22,25等非素数.我现在一遍又一遍地重新检查了几个小时,但仍然无法弄清楚我哪里出错了......请帮忙!
这是我的代码:
from math import sqrt
y=[2]
x=3
while len(y)!=100:
for i in range (2,int(round(sqrt(x)+1))):
if x%i==0:
x=x+1
else:
y.append(x)
x=x+1
break
print(y)
Run Code Online (Sandbox Code Playgroud)
我会这样做的; 更多Pythonic:
y = [2]
x = 3
while len(y) < 100:
if all(x % i != 0 for i in range(2, int(round(sqrt(x) + 1)))):
y.append(x)
x = x + 1
print(y)
Run Code Online (Sandbox Code Playgroud)
该all()功能非常有用.
这与你所做的更相似; 请注意break声明及其作用:
from math import sqrt
y=[2]
x=3
while len(y) != 100:
is_prime = True
for i in range (2, int(round(sqrt(x) + 1))):
if x % i == 0:
x += 1
is_prime = False
break # this means that x is not prime and we can move on, note that break breaks only the for loop
if is_prime:
y.append(x)
x += 1
print(y)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
176 次 |
| 最近记录: |