In computing and mathematics, the modulo operation returns the remainder or signed remainder of a division, after one number is divided by another, the latter being called the modulus of the operation.

Given two positive numbers a and n, a modulo n (often 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" evaluates 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 9 divided by 3 has a quotient of 3 and a remainder of 0.

Although typically performed with a and n both being integers, many computing systems now allow other types of numeric operands. The range of values for an integer modulo operation of n is 0 to n − 1. a mod 1 is always 0.

When exactly one of a or n is negative, the basic 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 ≠ 0 {\displaystyle n\neq 0} satisfy the following conditions:

q ∈ Z a = n q + r ( n ≠ 0 ) | r | < | n | {\displaystyle {\begin{aligned}&q\in \mathbb {Z} \\&a=nq+r\quad (n\neq 0)\\&|r|<|n|\end{aligned}}}

This still leaves a sign ambiguity if the remainder is non-zero: two possible choices for the remainder occur, one negative and the other positive; that choice determines which of the two consecutive quotients must be used to satisfy equation (1). In number theory, the positive remainder is always chosen, but in computing, programming languages choose depending on the language and the signs of a or n. Standard Pascal and ALGOL 68, for example, 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 under § In programming languages for details). Some systems leave a modulo 0 undefined, though others define it as a.

  • Quotient (q) and remainder (r) as functions of dividend (a), using truncated division Many implementations use truncated division, for which the quotient is defined by q = trunc ⁡ ( a n ) {\displaystyle q=\operatorname {trunc} \left({\frac {a}{n}}\right)} where trunc {\displaystyle \operatorname {trunc} } is the integral part function (rounding toward zero), i.e. the truncation to zero significant digits. Thus according to equation (1), the remainder has the same sign as the dividend a so can take 2|n| − 1 values: r = a − n trunc ⁡ ( a n ) {\displaystyle r=a-n\operatorname {trunc} \left({\frac {a}{n}}\right)}
  • Quotient and remainder using floored division Donald Knuth promotes floored division, for which the quotient is defined by q = ⌊ a n ⌋ {\displaystyle q=\left\lfloor {\frac {a}{n}}\right\rfloor } where ⌊ ⌋ {\displaystyle \lfloor \,\rfloor } is the floor function (rounding down). Thus according to equation (1), the remainder has the same sign as the divisor n: r = a − n ⌊ a n ⌋ {\displaystyle r=a-n\left\lfloor {\frac {a}{n}}\right\rfloor }
  • Quotient and remainder using Euclidean division Raymond T. Boute promotes Euclidean division, for which the non-negative remainder r ∈ { 0 , 1 , 2... } {\displaystyle r\in \{0,1,2...\}} is defined by r := a − n q s u c h t h a t 0 ≤ r < | n | . {\displaystyle r:=a-nq\ \mathrm {such\ that} \ {\color {red}{0\leq r}}<|n|.} (Emphasis added.) Under this definition, we can say the following about the quotient q {\displaystyle q}: q = a − r n ∈ Z = sgn ( n ) ⋅ a − r | n | = sgn ( n ) ⋅ ( a | n | − r | n | ) = sgn ( n ) ⋅ ⌊ a | n | ⌋ {\displaystyle {\begin{aligned}q&={\frac {a-r}{n}}\in \mathbb {Z} \\&={\text{sgn}}(n)\cdot {\frac {a-r}{|n|}}\\&={\text{sgn}}(n)\cdot \left({\frac {a}{|n|}}-{\frac {r}{|n|}}\right)\\&={\text{sgn}}(n)\cdot \left\lfloor {\frac {a}{\left|n\right|}}\right\rfloor \end{aligned}}} where sgn is the sign function, ⌊ ⌋ {\displaystyle \lfloor \,\rfloor } is the floor function (rounding down), and a | n | ∈ Q {\displaystyle {\frac {a}{|n|}}\in \mathbb {Q} }, r | n | ∈ Q {\displaystyle {\frac {r}{|n|}}\in \mathbb {Q} } are rational numbers. Equivalently, one may instead define the quotient q ∈ Z {\displaystyle q\in \mathbb {Z} } as follows: q := sgn ⁡ ( n ) ⌊ a | n | ⌋ = { ⌊ a n ⌋ if n > 0 ⌈ a n ⌉ if n < 0 {\displaystyle q:=\operatorname {sgn}(n)\left\lfloor {\frac {a}{\left|n\right|}}\right\rfloor ={\begin{cases}\left\lfloor {\frac {a}{n}}\right\rfloor &{\text{if }}n>0\\\left\lceil {\frac {a}{n}}\right\rceil &{\text{if }}n<0\\\end{cases}}} where ⌈ ⌉ {\displaystyle \lceil \,\rceil } is the ceiling function (rounding up). Thus according to equation (1), the remainder r {\displaystyle r} is non-negative: r = a − n q = a − | n | ⌊ a | n | ⌋ {\displaystyle r=a-nq=a-|n|\left\lfloor {\frac {a}{\left|n\right|}}\right\rfloor }
  • Quotient and remainder using rounded division Common Lisp and IEEE 754 use rounded division, for which the quotient is defined by q = round ⁡ ( a n ) {\displaystyle q=\operatorname {round} \left({\frac {a}{n}}\right)} where round is the round function (rounding half to even). Thus according to equation (1), the remainder falls between − n 2 {\displaystyle -{\frac {n}{2}}} and n 2 {\displaystyle {\frac {n}{2}}}, and its sign depends on which side of zero it falls to be within these boundaries: r = a − n round ⁡ ( a n ) {\displaystyle r=a-n\operatorname {round} \left({\frac {a}{n}}\right)}
  • Quotient and remainder using ceiling division Common Lisp also uses ceiling division, for which the quotient is defined by q = ⌈ a n ⌉ {\displaystyle q=\left\lceil {\frac {a}{n}}\right\rceil } where ⌈⌉ is the ceiling function (rounding up). Thus according to equation (1), the remainder has the opposite sign of that of the divisor: r = a − n ⌈ a n ⌉ {\displaystyle r=a-n\left\lceil {\frac {a}{n}}\right\rceil }

If both the dividend and divisor are positive, then the truncated, floored, and Euclidean definitions agree. If the dividend is positive and the divisor is negative, then the truncated and Euclidean definitions agree. If the dividend is negative and the divisor is positive, then the floored and Euclidean definitions agree. If both the dividend and divisor are negative, then the truncated and floored definitions agree.

However, truncated division satisfies the identity ( − a ) / b = − ( a / b ) = a / ( − b ) {\displaystyle ({-a})/b={-(a/b)}=a/({-b})}.

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.

For environments lacking a similar function, any of the three definitions above can be used.

Common pitfalls

When the result of a modulo operation has the sign of the dividend (truncated definition), 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:

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):

Or with the binary arithmetic:

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 (assuming x is a positive integer, or using a non-truncating definition):

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

Examples:

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.

Compiler optimizations 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.

Optimizations for general constant-modulus operations also exist by calculating the division first using the constant-divisor optimization.

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. The properties involving multiplication, division, and exponentiation generally require that a and n are integers.

  • Identity: (a mod n) mod n = a mod n. nx mod n = 0 for all positive integer values of x. If p is a prime number which is not a divisor of b, then abp−1 mod p = a mod p, due to Fermat's little theorem.
  • 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), and undefined otherwise.
  • Inverse multiplication: [(ab mod n)(b−1 mod n)] mod n = a mod n.

In programming languages

Modulo operators in various programming languages
LanguageOperatorIntegerFloating-pointDefinition
ABAPMODYesYesEuclidean
ActionScript%YesYesTruncated
AdamodYesNoFloored
remYesNoTruncated
ALGOL 68÷×, ÷*, , %*, modYesNoEuclidean
AMPLmodYesNoTruncated
APL|YesYesFloored
AppleScriptmodYesYesTruncated
AutoLISPremYesYesTruncated
AWK%YesYesTruncated (same as fmod in C)
BASICModYesNoVaries by implementation
bc%YesNoTruncated
C C++%, divYesNoTruncated
fmod (C) std::fmod (C++)NoYesTruncated
remainder (C) std::remainder (C++)NoYesRounded
C#%YesYesTruncated
Math.IEEERemainderNoYesRounded
Clarion%YesNoTruncated
CleanremYesNoTruncated
ClojuremodYesNoFloored
remYesNoTruncated
COBOLFUNCTION MODYesNoFloored
FUNCTION REMYesYesTruncated
CoffeeScript%YesNoTruncated
%%YesNoFloored
ColdFusion%, MODYesNoTruncated
Common Intermediate Languagerem (signed)YesYesTruncated
rem.un (unsigned)YesNo—N/a
Common LispmodYesYesFloored
remYesYesTruncated
Crystal%, moduloYesYesFloored
remainderYesYesTruncated
CSSmod()YesYesFloored
rem()YesYesTruncated
D%YesYesTruncated
Dart%YesYesEuclidean
remainder()YesYesTruncated
Eiffel\\YesNoTruncated
Elixirrem/2YesNoTruncated
Integer.mod/2YesNoFloored
ElmmodByYesNoFloored
remainderByYesNoTruncated
ErlangremYesNoTruncated
math:fmod/2NoYesTruncated (same as C)
EuphoriaremainderYesYesTruncated
modYesYesFloored
F#%YesYesTruncated (same as C#)
Math.IEEERemainderNoYesRounded
FactormodYesYesTruncated
remYesYesEuclidean
FileMakerModYesNoFloored
ForthmodYesNoImplementation defined
fm/modYesNoFloored
sm/remYesNoTruncated
FortranmodYesYesTruncated
moduloYesYesFloored
FrinkmodYesNoFloored
Full BASICMODYesYesFloored
REMAINDERYesYesTruncated
GLSL%YesNoUndefined
modNoYesFloored
GameMaker Studio (GML)mod, %YesNoTruncated
GDScript (Godot)%YesNoTruncated
posmodYesNoEuclidean
fmodNoYesTruncated
fposmodNoYesEuclidean
Go%YesNoTruncated
math.ModNoYesTruncated
big.Int.ModYesNoEuclidean
big.Int.RemYesNoTruncated
Groovy%YesNoTruncated
HaskellmodYesNoFloored
remYesNoTruncated
Data.Fixed.mod' (GHC)NoYesFloored
Haxe%YesYesTruncated
HLSL%YesYesUndefined
J|YesNoFloored
Java%YesYesTruncated
Math.floorModYesNoFloored
JavaScript TypeScript%YesYesTruncated
JuliamodYesYesFloored
%, remYesYesTruncated
Kotlin%, remYesYesTruncated
modYesYesFloored
ksh%YesNoTruncated (same as POSIX sh)
fmodNoYesTruncated
LabVIEWmodYesYesTruncated
LibreOfficeMODYesYesFloored
LogoMODULOYesNoFloored
REMAINDERYesNoTruncated
Lua 5%YesYesFloored
Lua 4mod(x,y)YesYesTruncated
Liberty BASICMODYesNoTruncated
Mathcadmod(x,y)YesNoFloored
Maplee mod m (by default), modp(e, m)YesNoEuclidean
mods(e, m)YesNoRounded
frem(e, m)YesYesRounded
MathematicaMod[a, b]YesNoFloored
MATLABmodYesYesFloored
remYesYesTruncated
MaximamodYesNoFloored
remainderYesNoTruncated
Maya Embedded Language%YesNoTruncated
Microsoft ExcelMODYesYesFloored
MinitabMODYesNoFloored
Modula-2MODYesNoFloored
REMYesNoTruncated
MUMPS#YesNoFloored
Netwide Assembler (NASM, NASMX)%, div (unsigned)YesNo—N/a
%% (signed)YesNoImplementation-defined
NimmodYesNoTruncated
OberonMODYesNoFloored-like
Objective-C%YesNoTruncated (same as C99)
Object Pascal, DelphimodYesNoTruncated
OCamlmodYesNoTruncated
mod_floatNoYesTruncated
Occam\YesNoTruncated
Pascal (ISO-7185 and -10206)modYesNoEuclidean-like
Perl%YesNoFloored
POSIX::fmodNoYesTruncated
PHP%YesNoTruncated
fmodNoYesTruncated
PIC BASIC Pro\\YesNoTruncated
PL/ImodYesNoFloored (ANSI PL/I)
PowerShell%YesNoTruncated
Programming Code (PRC)MATH.OP - 'MOD; (\)'YesNoUndefined
ProgressmoduloYesNoTruncated
Prolog ()modYesNoFloored
remYesNoTruncated
PureBasic%, Mod(x,y)YesNoTruncated
PureScript`mod`YesNoEuclidean
Pure Data%YesNoTruncated (same as C)
modYesNoFloored
Python%YesYesFloored
math.fmodNoYesTruncated
math.remainderNoYesRounded
Q#%YesNoTruncated
R%%YesYesFloored
RacketmoduloYesNoFloored
remainderYesNoTruncated
Raku%NoYesFloored
RealBasicMODYesNoTruncated
ReasonmodYesNoTruncated
Rexx//YesYesTruncated
RPG%REMYesNoTruncated
Ruby%, modulo()YesYesFloored
remainder()YesYesTruncated
Rust%YesYesTruncated
rem_euclid()YesYesEuclidean
SASMODYesNoTruncated
Scala%YesYesTruncated
SchememoduloYesNoFloored
remainderYesNoTruncated
Scheme R6RSmodYesNoEuclidean
mod0YesNoRounded
flmodNoYesEuclidean
flmod0NoYesRounded
ScratchmodYesYesFloored
Seed7modYesYesFloored
remYesYesTruncated
SenseTalkmoduloYesNoFloored
remYesNoTruncated
sh (POSIX) (includes bash, mksh, &c.)%YesNoTruncated (same as C)
Smalltalk\\YesYesFloored
rem:YesYesTruncated
Snap!modYesNoFloored
Spin//YesNoFloored
Solidity%YesNoTruncated
SQL (SQL:1999)mod(x,y)YesNoTruncated
SQL (SQL:2011)%YesNoTruncated
Standard MLmodYesNoFloored
Int.remYesNoTruncated
Real.remNoYesTruncated
Statamod(x,y)YesNoEuclidean
Swift%YesNoTruncated
remainder(dividingBy:)NoYesRounded
truncatingRemainder(dividingBy:)NoYesTruncated
Tcl%YesNoFloored
fmod()NoYesTruncated (same as C)
tcsh%YesNoTruncated
Torque%YesNoTruncated
TuringmodYesNoFloored
Verilog (2001)%YesNoTruncated
VHDLmodYesNoFloored
remYesNoTruncated
VimL%YesNoTruncated
Visual BasicModYesNoTruncated
WebAssemblyi32.rem_u, i64.rem_u (unsigned)YesNo—N/a
i32.rem_s, i64.rem_s (signed)YesNoTruncated
x86 assemblyDIV (unsigned)YesNo—N/a
IDIV (signed)YesNoTruncated
FPREMNoYesTruncated
FPREM1NoYesRounded
XBase++%YesYesTruncated
Mod()YesYesFloored
Zig%, @remYesYesTruncated
@modYesYesFloored
Z3 theorem proverdiv, modYesNoEuclidean

In addition, many computer systems provide a divmod functionality, which produces the quotient and the remainder at the same time. Examples include the x86 architecture's DIV and IDIV instructions, the C programming language's div() function, and Python's divmod() function.

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 and d = 1 is particularly common.

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: 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 mod d ⁡ n = a − n ⌊ a − d n ⌋ . {\displaystyle a\operatorname {mod} _{d}n=a-n\left\lfloor {\frac {a-d}{n}}\right\rfloor .}

To see this, let x = a − n ⌊ a − d n ⌋ {\textstyle x=a-n\left\lfloor {\frac {a-d}{n}}\right\rfloor }. We first show that x mod n = a mod n. It is in general true that (a + bn) mod n = a mod n for all integers b; thus, this is true also in the particular case when b = − ⌊ a − d n ⌋ {\textstyle b=-\!\left\lfloor {\frac {a-d}{n}}\right\rfloor }; but that means that x mod n = ( a − n ⌊ a − d n ⌋ ) mod n = a mod n {\textstyle x{\bmod {n}}=\left(a-n\left\lfloor {\frac {a-d}{n}}\right\rfloor \right)\!{\bmod {n}}=a{\bmod {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 ⌊ a − d n ⌋ = k {\textstyle \left\lfloor {\frac {a-d}{n}}\right\rfloor =k}, thus x = a − n ⌊ a − d n ⌋ = a − n k = d + r {\textstyle 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 Mod[a, n, d] .

Implementing other modulo definitions using truncation

Despite the mathematical elegance of Knuth's floored division and Euclidean division, it is generally much more common to find a truncated division-based modulo in programming languages. Leijen provides the following algorithms for calculating the two divisions given a truncated integer division:

For both cases, the remainder can be calculated independently of the quotient, but not vice versa. The operations are combined here to save screen space, as the logical branches are the same.

See also

Notes

External links

  • , animation of a cyclic representation of multiplication tables (explanation in French)