如果2个整数为互质数,则返回true的Python函数

问题描述

我需要一些帮助来查找此功能中的错误:


def is_coprime(num_1,num_2):
    """Function that returns true if 2 integers are coprime. """
    if num_1 > num_2:
        small = num_2
    else:
        small = num_1
    for i in range(1,small + 1):
        if ((num_1 % i == 0) and (num_2 % i != 0)):
            gcd = i
        if (gcd == 1):
            return True
        else:
            return False

希望缩进效果还不错。我认为我的错误在于if条件,但我不知道是什么。

解决方法

可以使用math.gcd完成共质素:

import math

def is_coprime(x,y):
    return math.gcd(x,y) == 1

is_coprime(39,115)
True

is_coprime(115*89,115)                                                                                                                             
False

,

我建议这种方法:

def divisors(x):
    return {i for i in range(2,x//2 + 1) if not x % i}

def coprime(x,y):
    return divisors(x).isdisjoint(divisors(y))

它如何工作? divisors(x)返回所有大于1的除数的集合。 coprie(x,y)函数检查给定的集合是否不相交。

,

我会说你的算法不好。让我们来看一个简单的示例,首先假设:

num_1 = 2
num_2 = 3
small = 2

通过循环运行这些值:

for i in range(1,small + 1):
    if num_1 % i == 0 and num_2 % i != 0:
        gcd = i

第一次迭代:

i = 1
2 % 1 == 0 and 3 % 1 == 0

第二次(也是最后一次)迭代:

i = 2
2 % 2 = 0 and 3 % 2 != 0
    gcd = 2

答案错误! gcd(2,3)== 1

假设您不想使用@oppressionslayer建议的内置math.gcd(),我们可以在Wikipedia中查找GCD并使用recursive binary algorithm。由于我们只想知道数字是否为互质数,因此我们可以将该算法中的其中一条语句进行快捷方式(偶数检验),然后简单地返回False

def coprime(u,v):

    # simple cases (termination)
    if u == v:
        return u == 1

    if u == 0:
        return v == 1

    if v == 0:
        return u == 1

    # look for factors of 2
    if ~u & 1:  # u is even
        if v & 1:  # v is odd
            return coprime(u >> 1,v)

        return False

    if ~v & 1:  # v is even,u is odd
        coprime(u,v >> 1)

    # reduce larger argument
    if u > v:
        return coprime(u - v,v)

    return coprime(v - u,u)

一些简单的测试:

print(coprime(2,3))  # True
print(coprime(21,24))  # False
print(coprime(39,115))  # True
print(coprime(115*89,115))  # False

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...