n = int(input(""))
L = []
x = 0
c = 0
while x <= n - 1:
Numero = int(input(""))
for i in range(1, n + 1):
if(n % i == 0):
c += 1
if c != 2:
x += 1
else:
L.append(Numero)
x += 1
print(L)
while x <= n - 1: # x < n is more comprehensive than x <= n-1
# Also, semantically it should be "for" loop
# As DYZ mentioned, you need to reinitialize c at every iteration
Numero = int(input("")) # I guess it's an error since you never use it
for i in range(1, n + 1): # it's ok to stop once c > 2
# also, you only need to check up to x/2
# and since we know it'll match 1 and x,
# whole loop can be replaced by all()
if(n % i == 0): # as DYZ mentioined, it should be x % i
c += 1
if c != 2:
x += 1 # this statement is executed regardless of condition
else:
L.append(Numero) # I guess you mean L.append(x)
x += 1
在解决了所有这些问题之后,我们得到了如下结果:
for x in range(2, n+1):
if all(x%i != 0 for i in range(2, x/2+1)):
L.append(x)
或者,作为列表理解(请注意,现在我们只检查它是否可被发现的素数整除-复杂性的一个重大改进):
[L.append(x) for x in range(2, n+1) if all(x%i != 0 for i in L)]
简短代码回顾:
在解决了所有这些问题之后,我们得到了如下结果:
或者,作为列表理解(请注意,现在我们只检查它是否可被发现的素数整除-复杂性的一个重大改进):
对于
n==22
,我们得到:相关问题 更多 >
编程相关推荐