2013-07-19 13:11:40 +00:00
|
|
|
#!/usr/bin/env python
|
|
|
|
# encoding: utf-8
|
|
|
|
|
|
|
|
|
2014-02-27 17:02:34 +00:00
|
|
|
__all__ = ['gcd']
|
|
|
|
|
2013-07-19 13:11:40 +00:00
|
|
|
def gcd(a, b):
|
2013-08-07 23:12:11 +00:00
|
|
|
"""Compute gcd(a,b)
|
2013-07-19 13:11:40 +00:00
|
|
|
|
2013-08-07 23:12:11 +00:00
|
|
|
:param a: first number
|
|
|
|
:param b: second number
|
|
|
|
:returns: the gcd
|
2013-07-19 13:11:40 +00:00
|
|
|
|
2013-08-07 23:12:11 +00:00
|
|
|
"""
|
2014-02-22 09:12:05 +00:00
|
|
|
pos_a, _a = (a >= 0), abs(a)
|
|
|
|
pos_b, _b = (b >= 0), abs(b)
|
|
|
|
|
|
|
|
gcd_sgn = (-1 + 2*(pos_a or pos_b))
|
|
|
|
|
|
|
|
if _a > _b:
|
|
|
|
c = _a % _b
|
2013-08-07 23:12:11 +00:00
|
|
|
else:
|
2014-02-22 09:12:05 +00:00
|
|
|
c = _b % _a
|
2013-07-19 13:11:40 +00:00
|
|
|
|
2013-08-07 23:12:11 +00:00
|
|
|
if c == 0:
|
2014-02-22 09:12:05 +00:00
|
|
|
return gcd_sgn * min(_a,_b)
|
|
|
|
elif _a == 1:
|
|
|
|
return gcd_sgn * _b
|
|
|
|
elif _b == 1:
|
|
|
|
return gcd_sgn * _a
|
2013-08-07 23:12:11 +00:00
|
|
|
else:
|
2014-02-22 09:12:05 +00:00
|
|
|
return gcd_sgn * gcd(min(_a,_b), c)
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
print(gcd(3, 15))
|
|
|
|
print(gcd(3, 15))
|
|
|
|
print(gcd(-15, -3))
|
|
|
|
print(gcd(-3, -12))
|
2013-07-19 13:11:40 +00:00
|
|
|
|
|
|
|
|
|
|
|
# -----------------------------
|
|
|
|
# Reglages pour 'vim'
|
|
|
|
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:
|
2016-02-13 03:29:26 +00:00
|
|
|
# cursor: 16 del
|