Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 互质函数;需要解释range()_Python - Fatal编程技术网

Python 互质函数;需要解释range()

Python 互质函数;需要解释range(),python,Python,这个问题已经被问了无数次了,但我需要一个特定部分的解释,我在网上找到了一个答案: # 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

这个问题已经被问了无数次了,但我需要一个特定部分的解释,我在网上找到了一个答案:

# 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
    #*************************************
质数只能被单位和自身整除 #(1按惯例不被视为质数) def iPrime(n): ''检查整数n是否为素数'' #确保n是一个正整数 n=abs(int(n)) #0和1不是素数 如果n<2: 返回错误 #2是唯一的偶数素数 如果n==2: 返回真值 #所有其他偶数都不是素数 如果不是n&1: 返回错误 #范围从3开始,只需要增加n的平方根 #对于所有奇数 #*************本节************ 对于范围(3,int(n**0.5)+1,2)内的x: 如果n%x==0: 返回错误 返回真值 #*************************************
有人能解释一下这个部分是怎么工作的吗?我知道range()中的值是start、stop和step。假设我们用17作为n。开始值为3且(n**0.5)+1=5.12,这将是我们的停止值。由于步长值为2,因此x将为1。然后进入if n%x==0:部分,插入17%1==0:的值,结果为True,因此返回False。哪里出错了?

循环首先将x设置为3,然后测试n除以3时是否有余数

如果不是,它不是素数

如果是,循环将x增加2(步长值),因此现在x是5

n的值除以5,看是否有余数

如果不是,那就是最好的

如果是,我们再次回到循环中,x=7,然后x=9,以此类推


循环只检查奇数,直到平方根加上n中的一个,因为因子总是成对出现在平方根的任一侧。如果平方根之前没有因子,它就是素数。

“既然步长值是2,x就是1”-等等,你是怎么得到的?你自己说的:
range
的参数是start、stop和step。因此,
start==3
。我建议您使用,例如,或者自己单独测试该循环。现在还不清楚你是如何得出这些结论的。@juanpa.arrivillaga嗯,
步骤是2。
如果不是n&1
是一种不必要的模糊方法来检查2的整除性。