【问题标题】:What algorithm does Python employ in fractions.gcd()?Python 在 fractions.gcd() 中使用了什么算法?
【发布时间】:2011-02-27 02:31:12
【问题描述】:

我正在使用 Python v3.1 中的分数模块来计算最大公约数。我想知道使用什么算法。我猜是欧几里得方法,但想确定一下。文档 (http://docs.python.org/py3k/library/fractions.html?highlight=fractions.gcd#fractions.gcd) 没有帮助。有人能帮我介绍一下吗?

【问题讨论】:

    标签: python fractions greatest-common-divisor


    【解决方案1】:

    来自fractions python

    “3.5 版后已弃用:改用 math.gcd()。”

    我也在寻找算法。我希望它有所帮助。

    【讨论】:

      【解决方案2】:

      根据the 3.1.2 source code online,这里是gcd,定义在Python-3.1.2/Lib/fractions.py

      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 编写。

      【讨论】:

      • 如果您使用的是 IPython,您可以通过输入 gcd?? 立即查看源代码
      • 在 IPython 中实际上是:import fractions,然后是:fractions.gcd??
      猜你喜欢
      • 1970-01-01
      • 2018-09-07
      • 2012-12-10
      • 2013-09-15
      • 1970-01-01
      • 2016-09-20
      • 1970-01-01
      • 1970-01-01
      • 2012-05-15
      相关资源
      最近更新 更多