我正在阅读Jeff Knupp的博客,我偶然发现了这个简单的小脚本:
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'声明。那就是如果一个数字被传递给小于一的函数(因此不能成为素数),该函数甚至不会浪费时间来评估这个数字,对吧?
答案 0 :(得分:1)
The third is the step.它遍历每个奇数小于或等于输入的平方根(3,5,7等)。
答案 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))