Greatest common divisor or gcd is a mathematical expression to find the highest number which can divide both the numbers whose gcd has to be found with the resulting remainder as zero. It has many mathematical applications. Python has a inbuilt gcd function in the math module which can be used for this purpose.
It's in the standard library.
>>> from fractions import gcd
>>> gcd(20,8)
4
Source code from the inspect
module in Python 2.7:
>>> 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
As of Python 3.5, gcd
is in the math
module; the one in fractions
is deprecated. Moreover, inspect.getsource
no longer returns explanatory source code for either method.
The algorithms with m-n can runs awfully long.
This one performs much better:
def gcd(x, y):
while y != 0:
(x, y) = (y, x % y)
return x
This version of code utilizes Euclid's Algorithm for finding GCD.
def gcd_recursive(a, b):
if b == 0:
return a
else:
return gcd_recursive(b, a % b)
gcd = lambda m,n: m if not n else gcd(n,m%n)
using recursion,
def gcd(a,b):
return a if not b else gcd(b, a%b)
using while,
def gcd(a,b):
while b:
a,b = b, a%b
return a
using lambda,
gcd = lambda a,b : a if not b else gcd(b, a%b)
>>> gcd(10,20)
>>> 10
def gcd(m,n):
return gcd(abs(m-n), min(m, n)) if (m-n) else n
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With