diff --git a/pymath/arithmetic.py b/pymath/arithmetic.py index b559788..2b2cadd 100644 --- a/pymath/arithmetic.py +++ b/pymath/arithmetic.py @@ -10,19 +10,30 @@ def gcd(a, b): :returns: the gcd """ - if a > b: - c = a % b + 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 else: - c = b % a + c = _b % _a if c == 0: - return min(a,b) - elif a == 1: - return b - elif b == 1: - return a + return gcd_sgn * min(_a,_b) + elif _a == 1: + return gcd_sgn * _b + elif _b == 1: + return gcd_sgn * _a else: - return gcd(min(a,b), c) + 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)) # ----------------------------- diff --git a/test/test_arthmetic.py b/test/test_arthmetic.py new file mode 100644 index 0000000..f5cb2d6 --- /dev/null +++ b/test/test_arthmetic.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python +# encoding: utf-8 + + +import unittest + +from pymath import arithmetic + + + +class TestArithmetic(unittest.TestCase): + """Testing functions from pymath.arithmetic""" + + def test_gcd_commu(self): + self.assertEqual(arithmetic.gcd(3, 15), arithmetic.gcd(15,3)) + + def test_gcd1(self): + self.assertEqual(arithmetic.gcd(3, 15), 3) + + def test_gcd2(self): + self.assertEqual(arithmetic.gcd(14, 21), 7) + + def test_gcd_prem(self): + self.assertEqual(arithmetic.gcd(14, 19), 1) + + def test_gcd_neg(self): + self.assertEqual(arithmetic.gcd(3, -15), 3) + self.assertEqual(arithmetic.gcd(-3, -15), -3) + + +if __name__ == '__main__': + unittest.main() + + + + + +# ----------------------------- +# Reglages pour 'vim' +# vim:set autoindent expandtab tabstop=4 shiftwidth=4: +# cursor: 16 del +