Incomputing andmathematics, themodulo operation returns theremainder or signed remainder of adivision, after one number is divided by another, the latter being called themodulus of the operation.
Given two positive numbersa andn,a modulon (often abbreviated asa modn) is the remainder of theEuclidean division ofa byn, wherea is thedividend andn is thedivisor.[1]
For example, the expression "5 mod 2" evaluates to 1, because 5 divided by 2 has aquotient 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 witha andn both beingintegers, many computing systems now allow other types of numeric operands. The range of values for an integer modulo operation ofn is 0 ton − 1.a mod 1 is always 0.
When exactly one ofa orn is negative, the basic definition breaks down, andprogramming languages differ in how these values are defined.
Inmathematics, the result of themodulo operation is anequivalence class, and any member of the class may be chosen asrepresentative; however, the usual representative is theleast positive residue, the smallest non-negative integer that belongs to that class (i.e., the remainder of theEuclidean division).[2] 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 theprogramming language or the underlyinghardware.
In nearly all computing systems, the quotientq and the remainderr ofa divided byn satisfy the following conditions:
1 |
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 ofa orn.[a] StandardPascal andALGOL 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 ofn ora is negative (see the table under§ In programming languages for details). Some systems leavea modulo 0 undefined, though others define it asa.
Many implementations usetruncated division, for which the quotient is defined by
where is theintegral part function (rounding toward zero), i.e. thetruncation to zero significant digits.Thus according to equation (1), the remainder has thesame sign as the dividenda so can take2|n| − 1 values:
Donald Knuth[3] promotesfloored division, for which the quotient is defined by
where is thefloor function (rounding down).Thus according to equation (1), the remainder has thesame sign as the divisorn:
Raymond T. Boute[4] promotesEuclidean division, for which the quotient is defined by
wheresgn is thesign function, is thefloor function (rounding down), and is theceiling function (rounding up).Thus according to equation (1), the remainder isnon negative:
Common Lisp andIEEE 754 userounded division, for which the quotient is defined by
whereround is theround function (rounding half to even).Thus according to equation (1), the remainder falls between and, and its sign depends on which side of zero it falls to be within these boundaries:
Common Lisp also usesceiling division, for which the quotient is defined by
where ⌈⌉ is theceiling function (rounding up).Thus according to equation (1), the remainder has theopposite sign of that of the divisor:
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.[5][6]
Some calculators have amod() function button, and many programming languages have a similar function, expressed asmod(a,n), for example. Some also support expressions that use "%", "mod", or "Mod" as a modulo or remainderoperator, such asa % n
ora mod n
.
For environments lacking a similar function, any of the three definitions above can be used.
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 isodd, one might be inclined to test if the remainder by 2 is equal to 1:
boolis_odd(intn){returnn%2==1;}
But in a language where modulo has the sign of the dividend, that is incorrect, because whenn (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):
boolis_odd(intn){returnn%2!=0;}
Or with the binary arithmetic:
boolis_odd(intn){returnn&1;}
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 ofpowers of 2 can alternatively be expressed as abitwise AND operation (assumingx 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.[7]
Compiler optimizations may recognize expressions of the formexpression % constant
whereconstant
is a power of two and automatically implement them asexpression & (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 (includingC), unless the dividend is of anunsigned integer type. This is because, if the dividend is negative, the modulo will be negative, whereasexpression & (constant-1)
will always be positive. For these languages, the equivalencex % 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 theconstant-divisor optimization.
Some modulo operations can be factored or expanded similarly to other mathematical operations. This may be useful incryptography proofs, such as theDiffie–Hellman key exchange. The properties involving multiplication, division, and exponentiation generally require thata andn are integers.
Language | Operator | Integer | Floating-point | Definition |
---|---|---|---|---|
ABAP | MOD | Yes | Yes | Euclidean |
ActionScript | % | Yes | No | Truncated |
Ada | mod | Yes | No | Floored[8] |
rem | Yes | No | Truncated[8] | |
ALGOL 68 | ÷× ,mod | Yes | No | Euclidean |
AMPL | mod | Yes | No | Truncated |
APL | | [b] | Yes | Yes | Floored |
AppleScript | mod | Yes | No | Truncated |
AutoLISP | (rem d n) | Yes | No | Truncated |
AWK | % | Yes | No | Truncated |
bash | % | Yes | No | Truncated |
BASIC | Mod | Yes | No | Varies by implementation |
bc | % | Yes | No | Truncated |
C C++ | % ,div | Yes | No | Truncated[c] |
fmod (C)std::fmod (C++) | No | Yes | Truncated[11] | |
remainder (C)std::remainder (C++) | No | Yes | Rounded | |
C# | % | Yes | Yes | Truncated |
Math.IEEERemainder | No | Yes | Rounded[12] | |
Clarion | % | Yes | No | Truncated |
Clean | rem | Yes | No | Truncated |
Clojure | mod | Yes | No | Floored[13] |
rem | Yes | No | Truncated[14] | |
COBOL | FUNCTION MOD | Yes | No | Floored[15] |
FUNCTION REM | Yes | Yes | Truncated[15] | |
CoffeeScript | % | Yes | No | Truncated |
%% | Yes | No | Floored[16] | |
ColdFusion | % ,MOD | Yes | No | Truncated |
Common Intermediate Language | rem (signed) | Yes | Yes | Truncated[17] |
rem.un (unsigned) | Yes | No | — | |
Common Lisp | mod | Yes | Yes | Floored |
rem | Yes | Yes | Truncated | |
Crystal | % ,modulo | Yes | Yes | Floored |
remainder | Yes | Yes | Truncated | |
CSS | mod() | Yes | Yes | Floored[18] |
rem() | Yes | Yes | Truncated[19] | |
D | % | Yes | Yes | Truncated[20] |
Dart | % | Yes | Yes | Euclidean[21] |
remainder() | Yes | Yes | Truncated[22] | |
Eiffel | \\ | Yes | No | Truncated |
Elixir | rem/2 | Yes | No | Truncated[23] |
Integer.mod/2 | Yes | No | Floored[24] | |
Elm | modBy | Yes | No | Floored[25] |
remainderBy | Yes | No | Truncated[26] | |
Erlang | rem | Yes | No | Truncated |
math:fmod/2 | No | Yes | Truncated (same as C)[27] | |
Euphoria | mod | Yes | No | Floored |
remainder | Yes | No | Truncated | |
F# | % | Yes | Yes | Truncated |
Math.IEEERemainder | No | Yes | Rounded[12] | |
Factor | mod | Yes | No | Truncated |
FileMaker | Mod | Yes | No | Floored |
Forth | mod | Yes | No | Implementation defined |
fm/mod | Yes | No | Floored | |
sm/rem | Yes | No | Truncated | |
Fortran | mod | Yes | Yes | Truncated |
modulo | Yes | Yes | Floored | |
Frink | mod | Yes | No | Floored |
Full BASIC | MOD | Yes | Yes | Floored[28] |
REMAINDER | Yes | Yes | Truncated[29] | |
GLSL | % | Yes | No | Undefined[30] |
mod | No | Yes | Floored[31] | |
GameMaker Studio (GML) | mod ,% | Yes | No | Truncated |
GDScript (Godot) | % | Yes | No | Truncated |
fmod | No | Yes | Truncated | |
posmod | Yes | No | Euclidean | |
fposmod | No | Yes | Euclidean | |
Go | % | Yes | No | Truncated[32] |
math.Mod | No | Yes | Truncated[33] | |
big.Int.Mod | Yes | No | Euclidean[34] | |
big.Int.Rem | Yes | No | Truncated[35] | |
Groovy | % | Yes | No | Truncated |
Haskell | mod | Yes | No | Floored[36] |
rem | Yes | No | Truncated[36] | |
Data.Fixed.mod' (GHC) | No | Yes | Floored | |
Haxe | % | Yes | No | Truncated |
HLSL | % | Yes | Yes | Undefined[37] |
J | | [b] | Yes | No | Floored |
Java | % | Yes | Yes | Truncated |
Math.floorMod | Yes | No | Floored | |
JavaScript TypeScript | % | Yes | Yes | Truncated |
Julia | mod | Yes | Yes | Floored[38] |
% ,rem | Yes | Yes | Truncated[39] | |
Kotlin | % ,rem | Yes | Yes | Truncated[40] |
mod | Yes | Yes | Floored[41] | |
ksh | % | Yes | No | Truncated (same as POSIX sh) |
fmod | No | Yes | Truncated | |
LabVIEW | mod | Yes | Yes | Truncated |
LibreOffice | =MOD() | Yes | No | Floored |
Logo | MODULO | Yes | No | Floored |
REMAINDER | Yes | No | Truncated | |
Lua 5 | % | Yes | Yes | Floored |
Lua 4 | mod(x,y) | Yes | Yes | Truncated |
Liberty BASIC | MOD | Yes | No | Truncated |
Mathcad | mod(x,y) | Yes | No | Floored |
Maple | e mod m (by default),modp(e, m) | Yes | No | Euclidean |
mods(e, m) | Yes | No | Rounded | |
frem(e, m) | Yes | Yes | Rounded | |
Mathematica | Mod[a, b] | Yes | No | Floored |
MATLAB | mod | Yes | Yes | Floored |
rem | Yes | Yes | Truncated | |
Maxima | mod | Yes | No | Floored |
remainder | Yes | No | Truncated | |
Maya Embedded Language | % | Yes | No | Truncated |
Microsoft Excel | =MOD() | Yes | Yes | Floored |
Minitab | MOD | Yes | No | Floored |
Modula-2 | MOD | Yes | No | Floored |
REM | Yes | No | Truncated | |
MUMPS | # | Yes | No | Floored |
Netwide Assembler (NASM,NASMX) | % ,div (unsigned) | Yes | No | — |
%% (signed) | Yes | No | Implementation-defined[42] | |
Nim | mod | Yes | No | Truncated |
Oberon | MOD | Yes | No | Floored-like[d] |
Objective-C | % | Yes | No | Truncated (same as C99) |
Object Pascal,Delphi | mod | Yes | No | Truncated |
OCaml | mod | Yes | No | Truncated[43] |
mod_float | No | Yes | Truncated[44] | |
Occam | \ | Yes | No | Truncated |
Pascal (ISO-7185 and -10206) | mod | Yes | No | Euclidean-like[e] |
Perl | % | Yes | No | Floored[f] |
POSIX::fmod | No | Yes | Truncated | |
Phix | mod | Yes | No | Floored |
remainder | Yes | No | Truncated | |
PHP | % | Yes | No | Truncated[46] |
fmod | No | Yes | Truncated[47] | |
PICBASIC Pro | \\ | Yes | No | Truncated |
PL/I | mod | Yes | No | Floored (ANSI PL/I) |
PowerShell | % | Yes | No | Truncated |
Programming Code (PRC) | MATH.OP - 'MOD; (\)' | Yes | No | Undefined |
Progress | modulo | Yes | No | Truncated |
Prolog (ISO 1995) | mod | Yes | No | Floored |
rem | Yes | No | Truncated | |
PureBasic | % ,Mod(x,y) | Yes | No | Truncated |
PureScript | `mod` | Yes | No | Euclidean[48] |
Pure Data | % | Yes | No | Truncated (same as C) |
mod | Yes | No | Floored | |
Python | % | Yes | Yes | Floored |
math.fmod | No | Yes | Truncated | |
math.remainder | No | Yes | Rounded | |
Q# | % | Yes | No | Truncated[49] |
R | %% | Yes | Yes | Floored[50] |
Racket | modulo | Yes | No | Floored |
remainder | Yes | No | Truncated | |
Raku | % | No | Yes | Floored |
RealBasic | MOD | Yes | No | Truncated |
Reason | mod | Yes | No | Truncated |
Rexx | // | Yes | Yes | Truncated |
RPG | %REM | Yes | No | Truncated |
Ruby | % ,modulo() | Yes | Yes | Floored |
remainder() | Yes | Yes | Truncated | |
Rust | % | Yes | Yes | Truncated |
rem_euclid() | Yes | Yes | Euclidean[51] | |
SAS | MOD | Yes | No | Truncated |
Scala | % | Yes | Yes | Truncated |
Scheme | modulo | Yes | No | Floored |
remainder | Yes | No | Truncated | |
SchemeR6RS | mod | Yes | No | Euclidean[52] |
mod0 | Yes | No | Rounded[52] | |
flmod | No | Yes | Euclidean | |
flmod0 | No | Yes | Rounded | |
Scratch | mod | Yes | Yes | Floored |
Seed7 | mod | Yes | Yes | Floored |
rem | Yes | Yes | Truncated | |
SenseTalk | modulo | Yes | No | Floored |
rem | Yes | No | Truncated | |
sh (POSIX) (includesbash,mksh, &c.) | % | Yes | No | Truncated (same as C)[53] |
Smalltalk | \\ | Yes | No | Floored |
rem: | Yes | No | Truncated | |
Snap! | mod | Yes | No | Floored |
Spin | // | Yes | No | Floored |
Solidity | % | Yes | No | Truncated[54] |
SQL (SQL:1999) | mod(x,y) | Yes | No | Truncated |
SQL (SQL:2011) | % | Yes | No | Truncated |
Standard ML | mod | Yes | No | Floored |
Int.rem | Yes | No | Truncated | |
Real.rem | No | Yes | Truncated | |
Stata | mod(x,y) | Yes | No | Euclidean |
Swift | % | Yes | No | Truncated[55] |
remainder(dividingBy:) | No | Yes | Rounded[56] | |
truncatingRemainder(dividingBy:) | No | Yes | Truncated[57] | |
Tcl | % | Yes | No | Floored |
fmod() | No | Yes | Truncated (as C) | |
tcsh | % | Yes | No | Truncated |
Torque | % | Yes | No | Truncated |
Turing | mod | Yes | No | Floored |
Verilog (2001) | % | Yes | No | Truncated |
VHDL | mod | Yes | No | Floored |
rem | Yes | No | Truncated | |
VimL | % | Yes | No | Truncated |
Visual Basic | Mod | Yes | No | Truncated |
WebAssembly | i32.rem_u ,i64.rem_u (unsigned) | Yes | No | —[58] |
i32.rem_s ,i64.rem_s (signed) | Yes | No | Truncated[58] | |
x86 assembly | IDIV | Yes | No | Truncated |
XBase++ | % | Yes | Yes | Truncated |
Mod() | Yes | Yes | Floored | |
Zig | % ,@rem | Yes | Yes | Truncated[59] |
@mod | Yes | Yes | Floored | |
Z3 theorem prover | div ,mod | Yes | No | Euclidean |
In addition, many computer systems provide adivmod
functionality, which produces the quotient and the remainder at the same time. Examples include thex86 architecture'sIDIV
instruction, the C programming language'sdiv()
function, andPython'sdivmod()
function.
Sometimes it is useful for the result ofa modulon to lie not between 0 andn − 1, but between some numberd andd +n − 1. In that case,d is called anoffset andd = 1 is particularly common.
There does not seem to be a standard notation for this operation, so let us tentatively usea moddn. We thus have the following definition:[60]x =a moddn just in cased ≤x ≤d +n − 1 andx modn =a modn. Clearly, the usual modulo operation corresponds to zero offset:a modn =a mod0n.
The operation of modulo with offset is related to thefloor function as follows:
To see this, let. We first show thatx modn =a modn. It is in general true that(a +bn) modn =a modn for all integersb; thus, this is true also in the particular case when; but that means that, which is what we wanted to prove. It remains to be shown thatd ≤x ≤d +n − 1. Letk andr be the integers such thata −d =kn +r with0 ≤r ≤n − 1 (seeEuclidean division). Then, thus. Now take0 ≤r ≤n − 1 and addd to both sides, obtainingd ≤d +r ≤d +n − 1. But we've seen thatx =d +r, so we are done.
The modulo with offseta moddn is implemented inMathematica asMod[a, n, d]
.[60]
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:
/* Euclidean and Floored divmod, in the style of C's ldiv() */typedefstruct{/* This structure is part of the C stdlib.h, but is reproduced here for clarity */longintquot;longintrem;}ldiv_t;/* Euclidean division */inlineldiv_tldivE(longnumer,longdenom){/* The C99 and C++11 languages define both of these as truncating. */longq=numer/denom;longr=numer%denom;if(r<0){if(denom>0){q=q-1;r=r+denom;}else{q=q+1;r=r-denom;}}return(ldiv_t){.quot=q,.rem=r};}/* Floored division */inlineldiv_tldivF(longnumer,longdenom){longq=numer/denom;longr=numer%denom;if((r>0&&denom<0)||(r<0&&denom>0)){q=q-1;r=r+denom;}return(ldiv_t){.quot=q,.rem=r};}
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.
α|ω
computes, the remainder when dividingω
byα
.%
to be truncated.[9] The standards before then leave the behavior implementation-defined.[10]div
andmod
do not obey the Division Identity ofD =d · (D /d) +D %d, and are thus fundamentally broken.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
Thefmod function returns the valuex - i * y, for some integeri such that, ify is nonzero, the result has the same sign asx and magnitude less than the magnitude ofy.
{{cite book}}
: CS1 maint: numeric names: authors list (link){{cite book}}
: CS1 maint: numeric names: authors list (link)X modulo Y, i.e., X-Y*INT(X/Y).
The remainder function, i.e., X-Y*IP(X/Y).
If both operands are non-negative, then the remainder is non-negative. Results are undefined if one or both operands are negative.
The % operator is defined only in cases where either both sides are positive or both sides are negative. Unlike C, it also operates on floating-point data types, as well as integers.