[英]wanted to have a single list instead of multiple list showing prime numbers
我試圖制作一個程序,顯示所有質數直到極限,但代碼顯示添加到ans
列表的每個因素。 我該如何解決?
limit = 34
num = [value for value in range(2, limit + 1)]
factor = 2
ans = []
while True:
if factor not in num:
factor += 1
elif factor in num:
ans.append(factor)
for ele in num:
if ele % factor == 0:
num.remove(ele)
print(ans)
預期產出
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
您需要確保factor
變量是有界的。
limit = 34
num = list(range(2, limit + 1))
factor = 2
ans = []
while factor <= limit+1:
if factor not in num:
factor += 1
elif factor in num:
ans.append(factor)
for ele in num:
if ele % factor == 0:
num.remove(ele)
print(ans)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.