def mod_div(n, d, m):
    """Returns (n/d) mod m. Works because the modular multiplicative
    inverse of d is equal to d^(m-2) mod m as long as m is prime."""

    inverse = pow(d, m-2, m)
    return (n*inverse) % m