Modulo

Computational operation


title: "Modulo" type: doc version: 1 created: 2026-02-28 author: "Wikipedia contributors" status: active scope: public tags: ["computer-arithmetic", "articles-with-example-c++-code", "operators-(programming)", "modular-arithmetic", "operations-on-numbers"] description: "Computational operation" topic_path: "general/computer-arithmetic" source: "https://en.wikipedia.org/wiki/Modulo" license: "CC BY-SA 4.0" wikipedia_page_id: 0 wikipedia_revision_id: 0

::summary Computational operation ::

::callout[type=note] the binary operation mod(a,n) ::

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 \neq 0 satisfy the following conditions: &q \in \mathbb{Z} \ &a = n q + r \quad (n \neq 0) \ &|r| \end{align}|}}

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 for details). Some systems leave a modulo 0 undefined, though others define it as a.

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

Notation

::callout[type=note] the binary mod operation ::

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 or .

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:

::code[lang=cpp] 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):

::code[lang=cpp] bool is_odd(int n) { return n % 2 != 0; } ::

Or with the binary arithmetic: ::code[lang=cpp] bool is_odd(int n) { return n & 1; } ::

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

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 where is a power of two and automatically implement them as , 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 will always be positive. For these languages, the equivalence x % 2n == x n - 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.

In programming languages

::data[format=table title="Modulo operators in various programming languages"]

LanguageOperatorIntegerFloating-pointDefinition
ABAPEuclidean
ActionScriptTruncated
Adatitle=ISO/IEC 8652:2012 - Information technology — Programming languages — Ada
Truncated
ALGOL 68, , , , **mod**Euclidean
AMPLTruncated
APL``
AppleScriptTruncated
AutoLISPTruncated
AWKTruncated (same as in C)
BASICVaries by implementation
bcTruncated
CC++,Truncated
(C) (C++)Truncated
(C) (C++)Rounded
C#Truncated
last=dotnet-bottitle=Math.IEEERemainder(Double, Double) Method (System)
ClarionTruncated
CleanTruncated
ClojureFloored
Truncated
COBOLtitle=ISO/IEC 1989:2023 – Programming language COBOL
Truncated
CoffeeScriptTruncated
Floored
ColdFusion,Truncated
Common Intermediate Language(signed)Truncated
(unsigned)
Common Lisptitle=CLHS: Function MOD, REM
Truncated
Crystal,Floored
Truncated
CSSFloored
Truncated
DTruncated
DartEuclidean
Truncated
EiffelTruncated
ElixirTruncated
Floored
ElmFloored
Truncated
ErlangTruncated
Truncated (same as C)
EuphoriaTruncated
Floored
F#Truncated (same as C#)
Rounded
FactorTruncated
Euclidean
FileMakerFloored
ForthImplementation defined
Floored
Truncated
FortranTruncated
Floored
FrinkFloored
Full BASICFloored
Truncated
GLSLUndefined
Floored
GameMaker Studio (GML),Truncated
GDScript (Godot)Truncated
Euclidean
Truncated
Euclidean
GoTruncated
Truncated
Euclidean
Truncated
GroovyTruncated
Haskelltitle=6 Predefined Types and Classes
Truncated
(GHC)Floored
HaxeTruncated
HLSLUndefined
J``
JavaTruncated
Floored
JavaScriptTypeScriptTruncated
JuliaFloored
,Truncated
Kotlin,Truncated
Floored
kshTruncated (same as POSIX )
Truncated
LabVIEWTruncated
LibreOfficeFloored
LogoFloored
Truncated
Lua 5Floored
Lua 4Truncated
Liberty BASICTruncated
MathcadFloored
Maple(by default),Euclidean
Rounded
Rounded
MathematicaFloored
MATLABFloored
Truncated
MaximaFloored
Truncated
Maya Embedded LanguageTruncated
Microsoft ExcelFloored
MinitabFloored
Modula-2Floored
Truncated
MUMPSFloored
Netwide Assembler (NASM, NASMX), (unsigned)
(signed)Implementation-defined
NimTruncated
OberonFloored-like
Objective-CTruncated (same as C99)
Object Pascal, DelphiTruncated
OCamlTruncated
Truncated
OccamTruncated
Pascal (ISO-7185 and -10206)Euclidean-like
PerlFloored
Truncated
PHPTruncated
Truncated
PIC BASIC ProTruncated
PL/IFloored (ANSI PL/I)
PowerShellTruncated
Programming Code (PRC)Undefined
ProgressTruncated
Prolog (ISO 1995)Floored
Truncated
PureBasic,Truncated
PureScriptEuclidean
Pure DataTruncated (same as C)
Floored
PythonFloored
Truncated
Rounded
Q#Truncated
RFloored
RacketFloored
Truncated
RakuFloored
RealBasicTruncated
ReasonTruncated
RexxTruncated
RPGTruncated
Ruby,Floored
Truncated
RustTruncated
Euclidean
SASTruncated
ScalaTruncated
SchemeFloored
Truncated
Scheme R6RSEuclidean
Rounded
Euclidean
Rounded
ScratchFloored
Seed7Floored
Truncated
SenseTalkFloored
Truncated
(POSIX) (includes bash, mksh, &c.)Truncated (same as C)
Smalltalktitle=ANSI INCITS 319-1998 (R2002): Information Technology - Programming Languages - Smalltalk
at=sec. 5.6.2.30}}
Snap!Floored
SpinFloored
SolidityTruncated
SQL (SQL:1999)Truncated
SQL (SQL:2011)Truncated
Standard MLFloored
Truncated
Truncated
StataEuclidean
SwiftTruncated
Rounded
Truncated
TclFloored
Truncated (same as C)
tcshTruncated
TorqueTruncated
TuringFloored
Verilog (2001)Truncated
VHDLFloored
Truncated
VimLTruncated
Visual BasicTruncated
WebAssembly, (unsigned)editor-first1=Andreas
, (signed)Truncated
x86 assemblyTruncated
XBase++Truncated
Floored
Zig,Truncated
Floored
Z3 theorem prover,Euclidean
::

In addition, many computer systems provide a functionality, which produces the quotient and the remainder at the same time. Examples include the x86 architecture's instruction, the C programming language's function, and Python's 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 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: just in case dxd + n − 1 and . Clearly, the usual modulo operation corresponds to zero offset: .

The operation of modulo with offset is related to the floor function as follows: a \operatorname{mod}_d n = a - n \left\lfloor\frac{a-d}{n}\right\rfloor.

To see this, let x = a - n \left\lfloor\frac{a-d}{n}\right\rfloor. We first show that . It is in general true that for all integers b; thus, this is true also in the particular case when b = -!\left\lfloor\frac{a-d}{n}\right\rfloor; but that means that 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 with 0 ≤ rn − 1 (see Euclidean division). Then \left\lfloor\frac{a-d}{n}\right\rfloor = k, thus x = a - n \left\lfloor\frac{a-d}{n}\right\rfloor = a - n k = d +r. Now take 0 ≤ rn − 1 and add d to both sides, obtaining dd + rd + n − 1. But we've seen that , so we are done.

The modulo with offset a modd n is implemented in Mathematica as  .

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:

::code[lang=c] /* Euclidean and Floored divmod, in the style of C's ldiv() / typedef struct { / This structure is part of the C stdlib.h, but is reproduced here for clarity */ long int quot; long int rem; } ldiv_t;

/* Euclidean division / inline ldiv_t ldivE(long numer, long denom) { / The C99 and C++11 languages define both of these as truncating. */ long q = numer / denom; long r = 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 */ inline ldiv_t ldivF(long numer, long denom) { long q = numer / denom; long r = 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.

The other modes of rounding are: ::code[lang=c] /* Round-division */ ldiv_t ldivR(long numer, long denom) {

}

/* Ceiling-division */ ldiv_t ldivC(long numer, long denom) {

} ::

--

Notes

References

References

  1. Weisstein, Eric W.. "Congruence".
  2. Caldwell, Chris. "residue".
  3. Knuth, Donald. E.. (1972). "The Art of Computer Programming". Addison-Wesley.
  4. Boute, Raymond T.. (April 1992). "The Euclidean definition of the functions div and mod". ACM Press (New York, NY, USA).
  5. (5 July 2001). "Mod Function and Negative Numbers".
  6. "Ada 83 LRM, Sec 4.5: Operators and Expression Evaluation".
  7. Horvath, Adam. (July 5, 2012). "Faster division and modulo operation - the power of two".
  8. (2024). "ABAP Keyword Documentation".
  9. "Operators - Adobe ActionScript® 3 (AS3) API Reference".
  10. (2012). "ISO/IEC 8652:2012 - Information technology — Programming languages — Ada". [[International Organization for Standardization.
  11. (1973). "Revised Report on the Algorithmic Language Algol 68". [[IFIP Working Group 2.1.
  12. "awk".
  13. (2005-05-06). "C99 specification (ISO/IEC 9899:TC2)".
  14. (2003). "ISO/IEC 14882:2003: Programming languages – C++". [[International Organization for Standardization]] (ISO), [[International Electrotechnical Commission]] (IEC).
  15. (1990). "ISO/IEC 9899:1990: Programming languages – C". [[International Organization for Standardization.
  16. (1999). "ISO/IEC 9899:1999: Programming languages — C". [[International Organization for Standardization.
  17. "Expressions - C# language specification".
  18. dotnet-bot. "Math.IEEERemainder(Double, Double) Method (System)".
  19. "clojure.core - Clojure v1.10.3 API documentation".
  20. "clojure.core - Clojure v1.10.3 API documentation".
  21. ((ISO/IEC JTC 1/SC 22/WG 4)). (January 2023). "ISO/IEC 1989:2023 – Programming language COBOL". [[ISO]].
  22. [http://coffeescript.org/#operators CoffeeScript operators]
  23. ((ISO/IEC JTC 1/SC 22)). (February 2012). "ISO/IEC 23271:2012 — Information technology — Common Language Infrastructure (CLI)". [[ISO]].
  24. "CLHS: Function MOD, REM".
  25. (2024-06-22). "mod() - CSS: Cascading Style Sheets {{!}} MDN".
  26. (2024-10-15). "rem() - CSS: Cascading Style Sheets {{!}} MDN".
  27. "Expressions - D Programming Language".
  28. "operator % method - num class - dart:core library - Dart API".
  29. "remainder method - num class - dart:core library - Dart API".
  30. "Kernel — Elixir v1.11.3".
  31. "Integer — Elixir v1.11.3".
  32. "Basics - core 1.0.5".
  33. "Basics - core 1.0.5".
  34. "Erlang -- math".
  35. "OpenEuphoria: Euphoria v4.0".
  36. "OpenEuphoria: Euphoria v4.0".
  37. "18. The F# Library FSharp.Core.dll - F# Language Specification".
  38. "mod ( x y -- z ) - Factor Documentation".
  39. "rem ( x y -- z ) - Factor Documentation".
  40. [[ANSI]]. (28 January 1987). "Programming Languages — Full BASIC". American National Standards Institute.
  41. [[ANSI]]. (28 January 1987). "Programming Languages — Full BASIC". American National Standards Institute.
  42. "GLSL Language Specification, Version 4.50.7".
  43. "GLSL Language Specification, Version 4.50.7".
  44. "int".
  45. "@GlobalScope".
  46. "@GlobalScope".
  47. "@GlobalScope".
  48. "The Go Programming Language Specification - The Go Programming Language".
  49. "math package - math - pkg.go.dev".
  50. "big package - math/big - pkg.go.dev".
  51. "big package - math/big - pkg.go.dev".
  52. "6 Predefined Types and Classes".
  53. "Binary Operators".
  54. . (30 June 2021). ["Operators"](https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-operators#additive-and-multiplicative-operators). *[[Microsoft]]*.
  55. "Mathematics · The Julia Language".
  56. "Mathematics · The Julia Language".
  57. "rem - Kotlin Programming Language".
  58. "mod - Kotlin Programming Language".
  59. "Mathematical Functions".
  60. "mod - Remainder after division (modulo operation) - MATLAB".
  61. "rem - Remainder after division - MATLAB".
  62. "MOD function - Microsoft Support".
  63. "Chapter 3: The NASM Language".
  64. "OCaml library : Stdlib".
  65. "OCaml library : Stdlib".
  66. [http://perldoc.perl.org/perlop.html#Multiplicative-Operators Perl documentation]
  67. "PHP: Arithmetic Operators - Manual".
  68. "PHP: fmod - Manual".
  69. "EuclideanRing".
  70. "6. Expressions".
  71. "math — Mathematical functions".
  72. "math — Mathematical functions".
  73. QuantumWriter. "Expressions".
  74. "R: Arithmetic Operators".
  75. "Operator expressions - The Rust Reference".
  76. "F32 - Rust".
  77. [http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_sec_11.7.3.1 r6rs.org]
  78. "Shell Command Language".
  79. (1998). "ANSI INCITS 319-1998 (R2002): Information Technology - Programming Languages - Smalltalk". [[American National Standards Institute]] (ANSI).
  80. "Solidity Documentation".
  81. "Apple Developer Documentation".
  82. "Apple Developer Documentation".
  83. "Apple Developer Documentation".
  84. (19 April 2022). "WebAssembly Core Specification: Version 2.0". [[World Wide Web Consortium]].
  85. "Zig Documentation".
  86. . (2020). ["Mod"](https://reference.wolfram.com/language/ref/Mod.html). *[[Wolfram Research]]*.

::callout[type=info title="Wikipedia Source"] This article was imported from Wikipedia and is available under the Creative Commons Attribution-ShareAlike 4.0 License. Content has been adapted to SurfDoc format. Original contributors can be found on the article history page. ::

computer-arithmeticarticles-with-example-c++-codeoperators-(programming)modular-arithmeticoperations-on-numbers