What algorithm does Python employ in fractions.gcd()?

寵の児 提交于 2019-12-10 01:52:13

问题


I'm using the fractions module in Python v3.1 to compute the greatest common divisor. I would like to know what algorithm is used. I'm guessing the Euclidean method, but would like to be sure. The docs (http://docs.python.org/py3k/library/fractions.html?highlight=fractions.gcd#fractions.gcd) don't help. Can anybody clue me in?


回答1:


According to the 3.1.2 source code online, here's gcd as defined in 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

So yes, it's the Euclidean algorithm, written in pure Python.




回答2:


From fractions python

"Deprecated since version 3.5: Use math.gcd() instead."

I was looking for the algorithm as well. I hope it helped.



来源:https://stackoverflow.com/questions/2962640/what-algorithm-does-python-employ-in-fractions-gcd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!