代码是:
numP = 1
x = 3
y = int(input('Enter number of primes to be found: '))
while numP<=y:
for n in range(2, x):
for b in range(2, n):
if n % b == 0:
break
else:
# loop fell through without finding a factor
print (n)
x += 2
numP += 1
输出类似于(例如,对于y = 4):
2
2
3
2
3
5
2
3
5
7
我想避免重复并获得如下输出:
2
3
5
7
答案 0 :(得分:0)
如果将数据存储在一个集合中,则可以避免重复
答案 1 :(得分:0)
没有理由从2..x循环n。摆脱该循环,并将所有对'n'的引用替换为'x'。即:
def find_primes(y):
x = 3
numP = 0
while True:
for b in range(2, x):
if x % b == 0:
break
else:
# loop fell through without finding a factor
print (x)
numP += 1
if numP >= y:
return
x += 2