# How to calculate the modulo using the remainder?

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?

• Modulo is not a function that returns a number. But if it were it would be the remainder function.. If the remainder function is programmed to return negative numbers then just add $n$ to the result if the result is negative. But you should kind in mind that in mathematics modulo is not a function that returns an integer. It's one of a a finite number of equivalence classees into which integers may fall. – fleablood Jan 21 '20 at 18:53
• Modulo $2$ means even or odd. The remainder function might be programmed to sometime return $-1$. If so, just replace that with $1$. – fleablood Jan 21 '20 at 19:21
• Sorry, this may not be the right website to ask then. I don't have a background in mathematics, but in computer science, modulo is a function that takes 2 integers and returns an integer. See for example: 123 mod -20. – BenMorel Jan 21 '20 at 20:14

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.

• You could also do an if clause. If $r =a\% b< 0$ then $a \mod b = r + b$. Otherwise $a\mod b = r$. – fleablood Jan 22 '20 at 1:13
• This breaks my unit tests. A failing example: 1 mod -123 should return -122, but returns 1 using your algorithm. – BenMorel Jan 22 '20 at 22:32
• Oh... you are can have negative modulus? Um why should $1 \mod {-123} = -123$ instead $1$. What is your definition of modulus? And what is your definition of "remainder"? And what do you want the answer to be. This really seems like just bean pushing to me. – fleablood Jan 22 '20 at 22:38
• You overlooked this part: "Integers congruent to -122 mod -123: -245, -368, -491, -614, -737, -860, -983, -1106, -1229, -1352, ... ". Like I said. Modulus is not an operation that returns one value. To me mind $1\mod -123=1$ is a more desirable answer than $-122$ but they are both valid. It really depends on what you want the definition to be. To my mind $1 \mod x$ should ALWAYS be $1$ no matter what $x$ is. – fleablood Jan 22 '20 at 22:41
• TBH I don't know, I'm just following the convention used by the Google calculator and Wolfram Alpha. This article explains, I think, which kind of mod is expected in computer systems. – BenMorel Jan 22 '20 at 22:49