Skip to content

Commit 7b2c76d

Browse files
Merge pull request #250 from oscarbenjamin/pr_fmpq_gcd
fmpq: Add fmpq.gcd() method
2 parents 7c154a4 + 890f020 commit 7b2c76d

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/flint/test/test_all.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -845,6 +845,10 @@ def test_fmpq():
845845
assert raises(lambda: Q(1,2) / Q(0), ZeroDivisionError)
846846
assert raises(lambda: Q(1,2) / 0, ZeroDivisionError)
847847

848+
assert Q(2,3).gcd(Q(4,9)) == Q(2,9)
849+
assert Q(2,3).gcd(5) == Q(1,3)
850+
assert raises(lambda: Q(2,3).gcd([]), TypeError)
851+
848852
assert Q(5,3).floor() == flint.fmpz(1)
849853
assert Q(-5,3).floor() == flint.fmpz(-2)
850854
assert Q(5,3).ceil() == flint.fmpz(2)

src/flint/types/fmpq.pyx

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,24 @@ cdef class fmpq(flint_scalar):
288288
def __rtruediv__(s, t):
289289
return fmpq._div_(t, s)
290290

291+
def gcd(s, t):
292+
"""GCD of two rational numbers.
293+
294+
>>> fmpq(1,2).gcd(fmpq(3,4))
295+
1/4
296+
297+
The GCD is defined as the GCD of the numerators divided by the LCM of
298+
the denominators. This is consistent with ``fmpz.gcd()`` but not with
299+
``fmpq_poly.gcd()``.
300+
"""
301+
cdef fmpq r
302+
t = any_as_fmpq(t)
303+
if t is NotImplemented:
304+
raise TypeError("fmpq expected")
305+
r = fmpq.__new__(fmpq)
306+
fmpq_gcd(r.val, (<fmpq>s).val, (<fmpq>t).val)
307+
return r
308+
291309
def next(s, bint signed=True, bint minimal=True):
292310
"""
293311
Returns the next rational number after *s* as ordered by

0 commit comments

Comments
 (0)