2013-08-22 50 views
0

我讀傑夫Knupp的博客,我碰到這個簡單的小腳本傳來:試圖瞭解這個簡單的Python代碼

 

import math 

def is_prime(n): 
    if n > 1: 
     if n == 2: 
      return True 
     if n % 2 == 0: 
      return False 
     for current in range(3, int(math.sqrt(n) + 1), 2): 
      if n % current == 0: 
       return False 
     return True 
    return False 

print(is_prime(17)) 

 

(注:我添加了進口數學一開始你可以看到原來在這裏: http://www.jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/

這是非常簡單的,我得到它的大部分,但我不知道他使用範圍函數是怎麼回事。我從來沒有用過這種方式,也沒有人看到過這種方式,但是我是一個初學者。範圍函數具有三個參數意味着什麼?它如何完成初始測試?

此外(並且道歉,如果這是一個愚蠢的問題),但最後'返回False'的聲明。那是因爲如果一個數字被傳遞給小於1的函數(因此不能成爲素數),該函數甚至不會浪費時間來評估該數字,對嗎?

回答

1

The third is the step.它遍歷每個奇數小於或等於輸入的平方根(3,5,7等)。

+0

好的,謝謝你爲我清理。使用輸入的平方根的基本原理是什麼?素數不可能有超過其平方根的潛在因素嗎? –

+0

是的。正好一個。本身。 –

+0

當然。我的問題是:爲什麼使用sqrt + 1作爲範圍函數的上界是可以接受的?例如,我嘗試通過手動操作一些示例來了解正在發生的事情,例如,通過在459(17 X 27)處循環。我發現sqrt + 1總是比我使用的較小的數字大一點。但是如果我使用7919(這是首要的,但讓我們假設我還不知道),素數的什麼屬性讓我停止在sqrt + 1之後尋找因素? –

1
import math #import math module 

def is_prime(n): #define is_prime function and assign variable n to its argument (n = 17 in this example). 
    if n > 1: #check if n (its argument) is greater than one, if so, continue; else return False (this is the last return in the function). 
     if n == 2: #check if n equals 2, it so return True and exit. 
      return True 
     if n % 2 == 0: #check if the remainder of n divided by two equas 0, if so, return False (is not prime) and exit. 
      return False 
     for current in range(3, int(math.sqrt(n) + 1), 2): #use range function to generate a sequence starting with value 3 up to, but not including, the truncated value of the square root of n, plus 1. Once you have this secuence give me every other number (3, 5, 7, etc)  
      if n % current == 0: #Check every value from the above secuence and if the remainder of n divided by that value is 0, return False (it's not prime) 
       return False 
     return True #if not number in the secuence divided n with a zero remainder then n is prime, return True and exit. 
    return False 

print(is_prime(17)) 
+0

非常感謝,評論的代碼非常有幫助。你說範圍函數將從第一個值開始,但是不要指定它將以3開始? –