python - Python 中最大公约数的代码

标签 python

a 和 b 的最大公约数 (GCD) 是将它们除以无余数的最大数。

求两个数的 GCD 的一种方法是 Euclid 算法,该算法基于以下观察:如果 ra 除以 时的余数b,然后 gcd(a, b) = gcd(b, r)。作为基本情况,我们可以使用 gcd(a, 0) = a.

编写一个名为 gcd 的函数,它接受参数 ab 并返回它们的最大公约数。

最佳答案

它是 in the standard library .

>>> from fractions import gcd
>>> gcd(20,8)
4

来自 Python 2.7 中 inspect 模块的源代码:

>>> print inspect.getsource(gcd)
def gcd(a, b):
    """Calculate the Greatest Common Divisor of a and b.

    Unless b==0, the result will have the same sign as b (so that when
    b is divided by it, the result comes out positive).
    """
    while b:
        a, b = b, a%b
    return a

从 Python 3.5 开始,gcd is in the math module ; fractions 中的那个已被弃用。此外,inspect.getsource 不再返回任何一种方法的解释性源代码。

关于python - Python 中最大公约数的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11175131/

相关文章:

python - get_includes 找不到标准库头文件

python - celerybeat 从哪里获取它在启动期间显示的配置

python - 使用 BeautifulSoup 将 HTML 表格数据解析为字典

python - 给定一个列表,如何计算该列表中的项目?

python - 如果有 2 个字幕,说明会丢失,只有 1 个可以正常工作

python - 将 groupby 值转换为数组列表

python - TensorFlowDNNClassifier 类已弃用,但替换似乎不起作用?

python - 格式化字符串未使用的命名参数

python - 计算标记的特定 block

python - 在 Python 中实现钩子(Hook)或回调的首选方法是什么?