# Modulo operation

Quotient (q) and      remainder (r) as functions of dividend (a), using different algorithms

In computing, the modulo operation finds the remainder or signed remainder after division of one number by another (called the modulus of the operation).

Given two positive numbers, a and n, a modulo n (abbreviated as a mod n) is the remainder of the Euclidean division of a by n, where a is the dividend and n is the divisor.

For example, the expression "5 mod 2" would evaluate to 1 because 5 divided by 2 has a quotient of 2 and a remainder of 1, while "9 mod 3" would evaluate to 0 because the division of 9 by 3 has a quotient of 3 and leaves a remainder of 0; there is nothing to subtract from 9 after multiplying 3 times 3. (Doing the division with a calculator will not show the result referred to here by this operation; the quotient will be expressed as a decimal fraction.)

Although typically performed with a and n both being integers, many computing systems allow other types of numeric operands. The range of numbers for an integer modulo of n is 0 to n − 1 inclusive. (a mod 1 is always 0; a mod 0 is undefined, possibly resulting in a division by zero error in programming languages.) See modular arithmetic for an older and related convention applied in number theory.

When either a or n is negative, the naive definition breaks down, and programming languages differ in how these values are defined.

## Variants of the definition

In mathematics, the result of the modulo operation is an equivalence class, and any member of the class may be chosen as representative; however, the usual representative is the least positive residue, the smallest non-negative integer that belongs to that class, i.e. the remainder of the Euclidean division. However, other conventions are possible. Computers and calculators have various ways of storing and representing numbers; thus their definition of the modulo operation depends on the programming language or the underlying hardware.

In nearly all computing systems, the quotient q and the remainder r of a divided by n satisfy

{\displaystyle {\begin{aligned}q\,&\in \mathbb {Z} \\a\,&=nq+r\\|r|\,&<|n|\end{aligned}}}

(1)

However, this still leaves a sign ambiguity if the remainder is nonzero: two possible choices for the remainder occur, one negative and the other positive, and two possible choices for the quotient occur. Usually, in number theory, the positive remainder is always chosen, but programming languages choose depending on the language and the signs of a or n.[1] Standard Pascal and ALGOL 68 give a positive remainder (or 0) even for negative divisors, and some programming languages, such as C90, leave it to the implementation when either of n or a is negative. See the table for details. a modulo 0 is undefined in most systems, although some do define it as a.

• Many implementations use truncated division, where the quotient is defined by truncation q = trunc(a/n) and thus according to equation (1) the remainder would have same sign as the dividend. The quotient is rounded towards zero: equal to the first integer in the direction of zero from the exact rational quotient.
${\displaystyle r=a-n\operatorname {trunc} \left({\frac {a}{n}}\right)}$
• Donald Knuth[1] described floored division where the quotient is defined by the floor function q = ⌊a/n and thus according to equation (1) the remainder would have the same sign as the divisor. Due to the floor function, the quotient is always rounded downwards, even if it is already negative.
${\displaystyle r=a-n\left\lfloor {\frac {a}{n}}\right\rfloor }$
• Raymond T. Boute[2] describes the Euclidean definition in which the remainder is nonnegative always, 0 ≤ r, and is thus consistent with the Euclidean division algorithm. In this case,
${\displaystyle n>0\Rightarrow q=\left\lfloor {\frac {a}{n}}\right\rfloor }$
${\displaystyle n<0\Rightarrow q=\left\lceil {\frac {a}{n}}\right\rceil }$

or equivalently

${\displaystyle q=\operatorname {sgn}(n)\left\lfloor {\frac {a}{\left|n\right|}}\right\rfloor }$

where sgn is the sign function, and thus

${\displaystyle r=a-|n|\left\lfloor {\frac {a}{\left|n\right|}}\right\rfloor }$
• Common Lisp also defines round-division and ceiling-division where the quotient is given by q = round(a/n) and q = ⌈a/n respectively.
• IEEE 754 defines a remainder function where the quotient is a/n rounded according to the round to nearest convention. Thus, the sign of the remainder is chosen to be nearest to zero.

As described by Leijen,

Boute argues that Euclidean division is superior to the other ones in terms of regularity and useful mathematical properties, although floored division, promoted by Knuth, is also a good definition. Despite its widespread use, truncated division is shown to be inferior to the other definitions.

— Daan Leijen, Division and Modulus for Computer Scientists[3]

However, Boute concentrates on the properties of the modulo operation itself and does not rate the fact that the truncated division shows the symmetry (-a) div n = -(a div n) and a div (-n) = -(a div n), which is similar to the ordinary division. As neither floor division nor Euclidean division offer this symmetry, Boute's judgement is at least incomplete.[citation needed][original research?]

## Common pitfalls

When the result of a modulo operation has the sign of the dividend, it can lead to surprising mistakes.

For example, to test if an integer is odd, one might be inclined to test if the remainder by 2 is equal to 1:

bool is_odd(int n) {
return n % 2 == 1;
}


But in a language where modulo has the sign of the dividend, that is incorrect, because when n (the dividend) is negative and odd, n mod 2 returns −1, and the function returns false.

One correct alternative is to test that the remainder is not 0 (because remainder 0 is the same regardless of the signs):

bool is_odd(int n) {
return n % 2 != 0;
}


Another is to use the fact that, for any odd number, the remainder may be either 1 or −1:

bool is_odd(int n) {
return n % 2 == 1 || n % 2 == -1;
}


## Notation

Some calculators have a mod() function button, and many programming languages have a similar function, expressed as mod(a, n), for example. Some also support expressions that use "%", "mod", or "Mod" as a modulo or remainder operator, such as

a % n

or

a mod n

or equivalent, for environments lacking a mod() function ('int' inherently produces the truncated value of a/n)

a - (n * int(a/n))

## Performance issues

Modulo operations might be implemented such that a division with a remainder is calculated each time. For special cases, on some hardware, faster alternatives exist. For example, the modulo of powers of 2 can alternatively be expressed as a bitwise AND operation:

x % 2n == x & (2n - 1)

Examples (assuming x is a positive integer):

x % 2 == x & 1
x % 4 == x & 3
x % 8 == x & 7

In devices and software that implement bitwise operations more efficiently than modulo, these alternative forms can result in faster calculations.[4]

Optimizing compilers may recognize expressions of the form expression % constant where constant is a power of two and automatically implement them as expression & (constant-1), allowing the programmer to write clearer code without compromising performance. This simple optimization is not possible for languages in which the result of the modulo operation has the sign of the dividend (including C), unless the dividend is of an unsigned integer type. This is because, if the dividend is negative, the modulo will be negative, whereas expression & (constant-1) will always be positive. For these languages, the equivalence x % 2n == x < 0 ? x | ~(2n - 1) : x & (2n - 1) has to be used instead, expressed using bitwise OR, NOT and AND operations.

## Properties (identities)

Some modulo operations can be factored or expanded similarly to other mathematical operations. This may be useful in cryptography proofs, such as the Diffie–Hellman key exchange.

• Identity:
• Inverse:
• [(−a mod n) + (a mod n)] mod n = 0.
• b−1 mod n denotes the modular multiplicative inverse, which is defined if and only if b and n are relatively prime, which is the case when the left hand side is defined: [(b−1 mod n)(b mod n)] mod n = 1.
• Distributive:
• (a + b) mod n = [(a mod n) + (b mod n)] mod n.
• ab mod n = [(a mod n)(b mod n)] mod n.
• Division (definition): a/b mod n = [(a mod n)(b−1 mod n)] mod n, when the right hand side is defined (that is when b and n are coprime). Undefined otherwise.
• Inverse multiplication: [(ab mod n)(b−1 mod n)] mod n = a mod n.

## In programming languages

Integer modulo operators in various programming languages
Language Operator Result has same sign as
ABAP MOD Nonnegative always
ActionScript % Dividend
Ada mod Divisor
rem Dividend
ALGOL 68 ÷×, mod Nonnegative always
AMPL mod Dividend
APL |[2] Divisor
AppleScript mod Dividend
AutoLISP (rem d n) Dividend
AWK % Dividend
BASIC Mod Undefined
bash % Dividend
bc % Dividend
C (ISO 1990) % Implementation-defined
div Dividend
C++ (ISO 1998) % Implementation-defined[5]
div Dividend
C (ISO 1999) %, div Dividend[6]
C++ (ISO 2011) %, div Dividend
C# % Dividend
Clarion % Dividend
Clean rem Dividend
Clojure mod Divisor
rem Dividend
COBOL[3] FUNCTION MOD Divisor
CoffeeScript % Dividend
%% Divisor[7]
ColdFusion %, MOD Dividend
Common Lisp mod Divisor
rem Dividend
Crystal % Dividend
D % Dividend[8]
Dart % Nonnegative always
remainder() Dividend
Eiffel \\ Dividend
Elixir rem Dividend
Elm modBy Divisor
remainderBy Dividend
Erlang rem Dividend
Euphoria mod Divisor
remainder Dividend
F# % Dividend
Factor mod Dividend
FileMaker Mod Divisor
Forth mod implementation defined
fm/mod Divisor
sm/rem Dividend
Fortran mod Dividend
modulo Divisor
Frink mod Divisor
GameMaker Studio (GML) mod, % Dividend
GDScript % Dividend
Go % Dividend
Groovy % Dividend
Haskell mod Divisor
rem Dividend
Haxe % Dividend
J |[4] Divisor
Java % Dividend
Math.floorMod Divisor
JavaScript % Dividend
Julia mod Divisor
%, rem Dividend
Kotlin %, rem Dividend
ksh % Dividend
LabVIEW mod Dividend
LibreOffice =MOD() Divisor
Logo MODULO Divisor
REMAINDER Dividend
Lua 5 % Divisor
Lua 4 mod(x,y) Divisor
Liberty BASIC MOD Dividend
Mathcad mod(x,y) Divisor
Maple e mod m Nonnegative always
Mathematica Mod[a, b] Divisor
MATLAB mod Divisor
rem Dividend
Maxima mod Divisor
remainder Dividend
Maya Embedded Language % Dividend
Microsoft Excel =MOD() Divisor
Minitab MOD Divisor
mksh % Dividend
Modula-2 MOD Divisor
REM Dividend
MUMPS # Divisor
Netwide Assembler (NASM, NASMX) %, div Modulo operator unsigned
%% Modulo operator signed
Nim mod Dividend
Oberon MOD Divisor[5]
Objective-C % Dividend
Object Pascal, Delphi mod Dividend
OCaml mod Dividend
Occam \ Dividend
Pascal (ISO-7185 and -10206) mod Nonnegative always[6]
Programming Code Advanced (PCA) \ Undefined
Perl % Divisor[7]
Phix mod Divisor
remainder Dividend
PHP % Dividend
PIC BASIC Pro \\ Dividend
PL/I mod Divisor (ANSI PL/I)
PowerShell % Dividend
Programming Code (PRC)  MATH.OP - 'MOD; (\)' Undefined
Progress modulo Dividend
Prolog (ISO 1995) mod Divisor
rem Dividend
PureBasic %, Mod(x,y) Dividend
PureScript mod Divisor
Python % Divisor
Q# % Dividend[9]
R %% Divisor
RealBasic MOD Dividend
Reason mod Dividend
Racket modulo Divisor
remainder Dividend
Rexx // Dividend
RPG %REM Dividend
Ruby %, modulo() Divisor
remainder() Dividend
Rust % Dividend
rem_euclid() Divisor
SAS MOD Dividend
Scala % Dividend
Scheme modulo Divisor
remainder Dividend
Scheme R6RS mod Nonnegative always[10]
mod0 Nearest to zero[10]
Scratch mod Divisor
Seed7 mod Divisor
rem Dividend
SenseTalk modulo Divisor
rem Dividend
Shell % Dividend
Smalltalk \\ Divisor
rem: Dividend
Snap! mod Divisor
Spin // Divisor
Solidity % Divisor
SQL (SQL:1999) mod(x,y) Dividend
SQL (SQL:2011) % Dividend
Standard ML mod Divisor
Int.rem Dividend
Stata mod(x,y) Nonnegative always
Swift % Dividend
Tcl % Divisor
TypeScript % Dividend
Torque % Dividend
Turing mod Divisor
Verilog (2001) % Dividend
VHDL mod Divisor
rem Dividend
VimL % Dividend
Visual Basic Mod Dividend
WebAssembly i32.rem_s, i64.rem_s Dividend
x86 assembly IDIV Dividend
XBase++ % Dividend
Mod() Divisor
Z3 theorem prover div, mod Nonnegative always
Floating-point modulo operators in various programming languages
Language Operator Result has same sign as
ABAP MOD Nonnegative always
C (ISO 1990) fmod Dividend[11]
C (ISO 1999) fmod Dividend
remainder Nearest to zero
C++ (ISO 1998) std::fmod Dividend
C++ (ISO 2011) std::fmod Dividend
std::remainder Nearest to zero
C# % Dividend
Common Lisp mod Divisor
rem Dividend
D % Dividend
Dart % Nonnegative always
remainder() Dividend
F# % Dividend
Fortran mod Dividend
modulo Divisor
Go math.Mod Dividend
Haskell (GHC) Data.Fixed.mod' Divisor
Java % Dividend
JavaScript % Dividend
ksh fmod Dividend
LabVIEW mod Dividend
Microsoft Excel =MOD() Divisor
OCaml mod_float Dividend
Perl POSIX::fmod Dividend
Raku % Divisor
PHP fmod Dividend
Python % Divisor
math.fmod Dividend
Rexx // Dividend
Ruby %, modulo() Divisor
remainder() Dividend
Rust % Dividend
rem_euclid() Divisor
Scheme R6RS flmod Nonnegative always
flmod0 Nearest to zero
Scratch mod Dividend
Standard ML Real.rem Dividend
Swift truncatingRemainder(dividingBy:) Dividend
XBase++ % Dividend
Mod() Divisor

## Generalizations

### Modulo with offset

Sometimes it is useful for the result of a modulo n to lie not between 0 and n−1, but between some number d and d+n−1. In that case, d is called an offset. There does not seem to be a standard notation for this operation, so let us tentatively use a modd n. We thus have the following definition:[12] x = a modd n just in case dxd+n−1 and x mod n = a mod n. Clearly, the usual modulo operation corresponds to zero offset: a mod n = a mod0 n. The operation of modulo with offset is related to the floor function as follows:

a modd n = ${\displaystyle a-n\left\lfloor {\frac {a-d}{n}}\right\rfloor }$.

(This is easy to see. Let ${\displaystyle x=a-n\left\lfloor {\frac {a-d}{n}}\right\rfloor }$. We first show that x mod n = a mod n. It is in genereal true that (a+bn) mod n = a mod n for all integers b; thus, this is true also in the particular case when b = ${\displaystyle -\left\lfloor {\frac {a-d}{n}}\right\rfloor }$; but that means that ${\displaystyle x\;{\text{mod}}\;n=\left(a-n\left\lfloor {\frac {a-d}{n}}\right\rfloor \right)\;{\text{mod}}\;n=a\;{\text{mod}}\;n}$, which is what we wanted to prove. It remains to be shown that dxd+n−1. Let k and r be the integers such that ad = kn + r with 0 ≤ rn-1 (see Euclidean division). Then ${\displaystyle \left\lfloor {\frac {a-d}{n}}\right\rfloor =k}$, thus ${\displaystyle x=a-n\left\lfloor {\frac {a-d}{n}}\right\rfloor =a-nk=d+r}$. Now take 0 ≤ rn−1 and add d to both sides, obtaining dd + rd+n−1. But we've seen that x = d + r, so we are done. □)

The modulo with offset a modd n is implemented in Mathematica as[12] Mod[a, n, d].

## Notes

• ^ Perl usually uses arithmetic modulo operator that is machine-independent. For examples and exceptions, see the Perl documentation on multiplicative operators.[13]
• ^ Mathematically, these two choices are but two of the infinite number of choices available for the inequality satisfied by a remainder.
• ^ Divisor must be positive, otherwise undefined.
• ^ As implemented in ACUCOBOL, Micro Focus COBOL, and possible others.
• ^ ^ Argument order reverses, i.e., α|ω computes ${\displaystyle \omega {\bmod {\alpha }}}$, the remainder when dividing ω by α.
• ^ As discussed by Boute, ISO Pascal's definitions of div and mod do not obey the Division Identity, and are thus fundamentally broken.

## References

1. ^ Knuth, Donald. E. (1972). The Art of Computer Programming. Addison-Wesley.
2. ^ Boute, Raymond T. (April 1992). "The Euclidean definition of the functions div and mod". ACM Transactions on Programming Languages and Systems. ACM Press (New York, NY, USA). 14 (2): 127–144. doi:10.1145/128861.128862.
3. ^ Leijen, Daan (December 3, 2001). "Division and Modulus for Computer Scientists" (PDF). Retrieved 2014-12-25.
4. ^ Horvath, Adam (July 5, 2012). "Faster division and modulo operation - the power of two".
5. ^ "ISO/IEC 14882:2003: Programming languages – C++". International Organization for Standardization (ISO), International Electrotechnical Commission (IEC). 2003. sec. 5.6.4. the binary % operator yields the remainder from the division of the first expression by the second. .... If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined Cite journal requires |journal= (help)
6. ^ "C99 specification (ISO/IEC 9899:TC2)" (PDF). 2005-05-06. sec. 6.5.5 Multiplicative operators. Retrieved 16 August 2018.
7. ^ CoffeeScript operators
8. ^ "Expressions". D Programming Language 2.0. Digital Mars. Retrieved 29 July 2010.
9. ^ QuantumWriter. "Expressions". docs.microsoft.com. Retrieved 2018-07-11.
10. ^ a b r6rs.org
11. ^ "ISO/IEC 9899:1990: Programming languages – C". ISO, IEC. 1990. sec. 7.5.6.4. The fmod function returns the value x - i * y, for some integer i such that, if y is nonzero, the result as the same sign as x and magnitude less than the magnitude of y. Cite journal requires |journal= (help)
12. ^ a b "Mod". Wolfram Language & System Documentation Center. Wolfram Research. 2020. Retrieved April 8, 2020.
13. ^ Perl documentation