алгоритм – What if the remainder of the division does not fit into the unsigned type?


I have two unsigned numbers and I need to find the remainder after dividing the sum of these numbers by the third, also unsigned number. How to do it carefully, given that the sum of two unsigned ones generally does not have to fit into the type in size (i.e. overflow is possible)


The algorithm might be like this. Take the remainder after dividing each dividend by the divisor. Then take the difference between the divisor and one of the remainders. Subtract this difference from the second remainder if it is greater than the second remainder, or add the remainders if they are less than the divisor and get the final remainder.

Let there be two unsigned numbers x and y and a divisor d . Then the remainder r when x + y is divided by d can be calculated as follows.

r1 = x % d;
r2 = y % d;

r = r1 < ( d - r2 ) ? r1 + r2 : r1 - ( d - r2 );

Here is an example function for type unsigned int in C/C++

unsigned int remainder(unsigned int x, unsigned int y, unsigned int d)
    unsigned int r1 = x % d;
    unsigned int r2 = y % d;

    return r1 < (d - r2) ? r1 + r2 : r1 - (d - r2);
Scroll to Top