def _g(x, multiplier, modulus):
    """
    An implementation of the G function that avoids overflows.
    :param x: (int) the current state of the generator.
    :param multiplier: (int) a valid multiplier w.r.t. modulus.
    :param modulus: (int) a prime number.
    :return: (int) the next state of the generator.
    """
    q = int(modulus / multiplier)
    r = int(modulus % multiplier)
    t = int(multiplier * (x % q) - r * int(x / q))
    if t > 0:
        return int(t)
    else:
        return int(t + modulus)