2013-08-22 53 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开始? –