Search code examples
pythongmp

Python gmpy2 f_divmod function confusion


I'm pretty new to python and i just started playing with gmpy2, but i'm a little confused about one of the functions and gmpy's documentation isn't helpful in this regard:

I'd like to do division with a modulus (as well as a floor) so i found the f_divmod() function:

f_divmod(...) f_divmod(x, y) returns the quotient and remainder of x divided by y. The quotient is rounded towards -Inf (floor rounding) and the remainder will have the same sign as y. x and y must be integers.

However if this does what i think it should do (and that is probably my mistake), it should do: x / y % m, and i see no way to provide an m. Is this the wrong function for that, or do i need to somehow define a modulus elsewhere?

I see my alternative being:

c = gmpy2.f_div(a, b) % m

Thanks in advance!


Solution

  • Note: I maintain gmpy2.

    gmpy2.f_divmod() (along with gmpy2.c_divmod(), gmpy2.t_divmod(), and gmpy2.divmod()) are patterned after the builtin divmod(). All the functions return the quotient and remainder but each functions uses a slightly different rule to compute the quotient and remainder. The names are meant to imply that the functions return the tuple (a // b, a % b). They don't do division followed by mod.

    If you want to calculate the quotient using floor division, and then reduce that result modulo another number, then your alternative is correct.

    Slightly off-topic hint: You should get into the habit of using // for integer division. In Python 3, / becomes floating point division. // is integer division in both Python 2 and 3.