[英]Printing prime numbers in range
k=int(input())
res=[2]
for i in range(2,k+1):
if i%2==0:
continue
else:
for j in range(2,i):
if i%j==0 or j%2==0 :
break
else:
res.append(i)
print(res)
此代碼用於在給定的數字范圍內查找素數。 我試圖運行代碼,但列表只有第 2 個。誰能告訴我發生了什么? 如果我刪除j%2==0
它正在工作。 我只想知道我的錯誤。
您應該使用當前的結果來加速您的過程。 您只需要測試素數的整除性。 但是你正在建立一個質數列表。 所以使用它!
k=int(input())
primes=[]
for i in range(2,k+1):
if all(i%p!=0 for p in primes):
primes.append(i)
您還可以通過僅選擇不如其他人建議的 sqrt(i) 的素數元素來改進。
import math
k=int(input())
primes=[]
for i in range(2,k+1):
j=math.sqrt(i)
if all(i%p!=0 for p in primes if p<=j):
primes.append(i)
在您的內部循環j
變量從值 2 開始,然后您有一個 if 語句始終為True
因為j%2==0
始終為2%2==0
始終為True
,因此您總是從第一步break
內部for
循環迭代
您可以使用:
import math
k=int(input())
res=[]
for i in range(2, k+1):
for x in range(2, int(math.sqrt(i) + 1)):
if i % x == 0 :
break
else:
res.append(i)
# k = 20
輸出:
[2, 3, 5, 7, 11, 13, 17, 19]
為了有效地生成素數,您可以使用埃拉托色尼篩法:
# Sieve of Eratosthenes
# Code by David Eppstein, UC Irvine, 28 Feb 2002
# http://code.activestate.com/recipes/117119/
def _gen_primes():
""" Generate an infinite sequence of prime numbers.
"""
# Maps composites to primes witnessing their compositeness.
# This is memory efficient, as the sieve is not "run forward"
# indefinitely, but only as long as required by the current
# number being tested.
#
D = {}
# The running integer that's checked for primeness
q = 2
while True:
if q not in D:
# q is a new prime.
# Yield it and mark its first multiple that isn't
# already marked in previous iterations
#
yield q
D[q * q] = [q]
else:
# q is composite. D[q] is the list of primes that
# divide it. Since we've reached q, we no longer
# need it in the map, but we'll mark the next
# multiples of its witnesses to prepare for larger
# numbers
#
for p in D[q]:
D.setdefault(p + q, []).append(p)
del D[q]
q += 1
k=int(input())
def gen_primes(k):
gp = _gen_primes()
p = next(gp)
while p < k:
yield p
p = next(gp)
res = list(gen_primes(k))
您的代碼有一個問題,在內部循環中 or 條件不正確,正如@kederrac 所強調的那樣。 您不需要 j%2==0 因為 j 總是從 2 開始,而i%j==0
已經涵蓋了條件
k=int(input())
res=[2]
for i in range(2,k+1):
if i%2==0:
continue
else:
for j in range(2,i):
if i%j==0 :
break
else:
res.append(i)
print(res)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.