Skip to content

fmpq: Add fmpq.gcd() method #250

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/flint/test/test_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -841,6 +841,10 @@ def test_fmpq():
assert raises(lambda: Q(1,2) / Q(0), ZeroDivisionError)
assert raises(lambda: Q(1,2) / 0, ZeroDivisionError)

assert Q(2,3).gcd(Q(4,9)) == Q(2,9)
assert Q(2,3).gcd(5) == Q(1,3)
assert raises(lambda: Q(2,3).gcd([]), TypeError)

assert Q(5,3).floor() == flint.fmpz(1)
assert Q(-5,3).floor() == flint.fmpz(-2)
assert Q(5,3).ceil() == flint.fmpz(2)
Expand Down
18 changes: 18 additions & 0 deletions src/flint/types/fmpq.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,24 @@ cdef class fmpq(flint_scalar):
def __rtruediv__(s, t):
return fmpq._div_(t, s)

def gcd(s, t):
"""GCD of two rational numbers.

>>> fmpq(1,2).gcd(fmpq(3,4))
1/4

The GCD is defined as the GCD of the numerators divided by the LCM of
the denominators. This is consistent with ``fmpz.gcd()`` but not with
``fmpq_poly.gcd()``.
"""
cdef fmpq r
t = any_as_fmpq(t)
if t is NotImplemented:
raise TypeError("fmpq expected")
r = fmpq.__new__(fmpq)
fmpq_gcd(r.val, (<fmpq>s).val, (<fmpq>t).val)
return r

def next(s, bint signed=True, bint minimal=True):
"""
Returns the next rational number after *s* as ordered by
Expand Down
Loading