Skip to content

Commit

Permalink
Use fractions.gcd in igcd
Browse files Browse the repository at this point in the history
  • Loading branch information
skirpichev committed Jul 26, 2016
1 parent cb670e2 commit ed01e16
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 26 deletions.
30 changes: 5 additions & 25 deletions diofant/core/numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,18 +128,11 @@ def _literal_float(f):
pat = r"[-+]?((\d*\.\d+)|(\d+\.?))(eE[-+]?\d+)?"
return bool(regex.match(pat, f))

# (a,b) -> gcd(a,b)
_gcdcache = {}

# TODO caching with decorator, but not to degrade performance


@cacheit
def igcd(*args):
"""Computes positive integer greatest common divisor.
The algorithm is based on the well known Euclid's algorithm. To
improve speed, igcd() has its own caching mechanism implemented.
Examples
========
Expand All @@ -148,27 +141,14 @@ def igcd(*args):
2
>>> igcd(5, 10, 15)
5
"""
a = args[0]
for b in args[1:]:
try:
a = _gcdcache[(a, b)]
except KeyError:
a, b = as_int(a), as_int(b)

if a and b:
if b < 0:
b = -b

while b:
a, b = b, a % b
else:
a = abs(a or b)
a, b = as_int(a), abs(as_int(b))

_gcdcache[(a, b)] = a
if a == 1 or b == 1:
return 1
a = fractions.gcd(a, b)
if a == 1:
break
return a


Expand Down
2 changes: 1 addition & 1 deletion diofant/core/tests/test_numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ def test_igcd():
assert igcd(7, 0) == 7
assert igcd(7, 1) == 1
assert igcd(1, 7) == 1
assert igcd(-1, 0) == 1
assert igcd(-1, 0) == -1
assert igcd(0, -1) == 1
assert igcd(-1, -1) == 1
assert igcd(-1, 7) == 1
Expand Down

0 comments on commit ed01e16

Please sign in to comment.