-2
這個問題已經被問了bajillion次,但我需要一個解釋上的特定部分的答案,我在網上找到:isPrime函數;的範圍解釋()需要
# prime numbers are only divisible by unity and themselves
# (1 is not considered a prime number by convention)
def isprime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up the squareroot of n
# for all odd numbers
# ************THIS SECTION************
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
#*************************************
有人能解釋這一部分是如何工作的?我明白range()中的值是開始,停止,一步。假設我們使用17作爲n。起始值是3,(n ** 0.5)+ 1 = 5.12,這將是我們的停止值。由於步長值爲2,因此x將爲1.然後,我們進入if n%x == 0:部分,並插入值爲17%1 == 0的值,結果爲True,所以我們返回False。我哪裏錯了?
「既然步長值是2,x就是1」 - 等等,你怎麼知道的? – user2357112
你自己說過:'range'的參數是_start_,stop和step。所以,'開始== 3'。 – ForceBru
我建議你使用例如http://pythontutor.com/,或者只是單獨測試那個循環。目前尚不清楚你如何得出這些結論。 – jonrsharpe