How to calculate the modulo using the remainder?

328 Views Asked by At

I'm writing an arbitrary-precision arithmetic library.

I have methods to calculate the quotient and remainder of a division.

I'd now like to add the modulo operator. Modulo and remainder are not the same for negative numbers.

How can I calculate the modulo of 2 numbers, using a remainder() function and other basic arithmetic operations?

1

There are 1 best solutions below

5
On BEST ANSWER

As found on https://www.lemoda.net/c/modulo-operator/ :

% being the remainder operator, the modulo can be calculated as:

((a % b) + b) % b

I successfully verified that the result is correct for all sign combinations of the dividend and the divisor.