Modulo Explained

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

Given two positive numbers and, modulo (often abbreviated as) is the remainder of the Euclidean division of by, where is the dividend and is the divisor.[1]

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 and both being integers, many computing systems now allow other types of numeric operands. The range of values for an integer modulo operation of is 0 to (mod 1 is always 0; is undefined, being a division by zero).

When exactly one of or 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).[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 the programming language or the underlying hardware.

In nearly all computing systems, the quotient and the remainder of divided by satisfy the following conditions:

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 or . 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 or is negative (see the table under for details). modulo 0 is undefined in most systems, although some do define it as .

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.

As described by Leijen,

However, truncated division satisfies the identity

({-a})/b={-(a/b)}=a/({-b})

.[3]

Notation

Some calculators have a function button, and many programming languages have a similar function, expressed as, 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:

bool is_odd(int n)

But in a language where modulo has the sign of the dividend, that is incorrect, because when (the dividend) is negative and odd, 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)

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

bool is_odd(int n)

A simpler alternative is to treat the result of n % 2 as if it is a Boolean value, where any non-zero value is true:

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

x % 2<sup>n</sup> == x & (2<sup>n</sup> - 1)

Examples:

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

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 % 2<sup>n</sup> == x < 0 ? x | ~(2<sup>n</sup> - 1) : x & (2<sup>n</sup> - 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 and are integers.

In programming languages

Modulo operators in various programming languages
LanguageOperatorIntegerFloating-pointDefinition
ABAPEuclidean
ActionScriptTruncated
AdaFloored[5]
Truncated
ALGOL 68, Euclidean
AMPLTruncated
APL<nowiki>|</nowiki>
| | | Floored

|-| AppleScript| | | | Truncated

|-| AutoLISP| | | | Truncated

|-| AWK| | | | Truncated

|-| bash| | | | Truncated

|-| BASIC| | | | Varies by implementation

|-| bc| | | | Truncated

|-| rowspan="3" | CC++|, | | | Truncated|-| (C) (C++)| | | Truncated[6] |-| (C) (C++)| | | Rounded

|-| rowspan="2" | C#| | | | Truncated|-| | | | Rounded[7]

|-| Clarion| | | | Truncated

|-| Clean| | | | Truncated

|-| rowspan="2" | Clojure| | | | Floored[8] |-| | | | Truncated[9]

|-| rowspan="2" | COBOL| | | | Floored[10] |-| | | | Truncated[10]

|-| rowspan="2" | CoffeeScript| | | | Truncated|-| | | | Floored[11]

|-| ColdFusion|, | | | Truncated

|-| rowspan="2" | Common Intermediate Language| (signed)| | | Truncated[12] |-| (unsigned)| | |

|-| rowspan="2" | Common Lisp| | | | Floored|-| | | | Truncated

|-| rowspan="2" | Crystal|, | | | Floored|-| | | | Truncated

|-| D| | | | Truncated[13]

|-| rowspan="2" | Dart| | | | Euclidean[14] |-| | | | Truncated[15]

|-| Eiffel| | | | Truncated

|-| rowspan="2" | Elixir| | | | Truncated[16] |-| | | | Floored[17]

|-| rowspan="2" | Elm| | | | Floored[18] |-| | | | Truncated[19]

|-| rowspan="2" | Erlang| | | | Truncated|-| | | | Truncated (same as C)[20]

|-| rowspan="2" | Euphoria| | | | Floored|-| | | | Truncated

|-| rowspan="2" | F#| | | | Truncated|-| | | | Rounded

|-| Factor| | | | Truncated

|-| FileMaker| | | | Floored

|-| rowspan="3" | Forth| | | | Implementation defined|-| | | | Floored|-| | | | Truncated

|-| rowspan="2" | Fortran| | | | Truncated|-| | | | Floored

|-| Frink| | | | Floored

|-| rowspan="2" | Full BASIC| | | | Floored[21] |-| | | | Truncated[22]

|-| rowspan="2" | GLSL| | | | Undefined[23] |-| | | | Floored[24]

|-| GameMaker Studio (GML)|, | | | Truncated

|-| rowspan="4" | GDScript (Godot)| | | | Truncated|-| | | | Truncated|-| | | | Euclidean|-| | | | Euclidean

|-| rowspan="4" | Go| | | | Truncated[25] |-| | | | Truncated[26] |-| | | | Euclidean[27] |-| | | | Truncated[28] |-| Groovy| | | | Truncated

|-| rowspan="3" | Haskell| | | | Floored[29] |-| | | | Truncated|-| (GHC)| | | Floored

|-| Haxe| | | | Truncated

|-| HLSL| | | | Undefined[30]

|-| J| <nowiki>|</nowiki>| | | Floored

|-| rowspan="2" | Java| | | | Truncated|-| | | | Floored

|-| JavaScriptTypeScript| | | | Truncated

|-| rowspan="2" | Julia| | | | Floored[31] |-|, | | | Truncated[32]

|-| rowspan="2" | Kotlin|, | | | Truncated[33] |-| | | | Floored[34]

|-| rowspan="2" | ksh| | | | Truncated (same as POSIX sh)|-| | | | Truncated

|-| LabVIEW| | | | Truncated

|-| LibreOffice| | | | Floored

|-| rowspan="2" | Logo| | | | Floored|-| | | | Truncated

|-| Lua 5| | | | Floored

|-| Lua 4| | | | Truncated

|-| Liberty BASIC| | | | Truncated

|-| Mathcad| | | | Floored

|-| rowspan="3" | Maple| (by default), | | | Euclidean|-| | | | Rounded|-| | | | Rounded

|-| Mathematica| | | | Floored

|-| rowspan="2" | MATLAB| | | | Floored|-| | | | Truncated

|-| rowspan="2" | Maxima| | | | Floored|-| | | | Truncated

|-| Maya Embedded Language| | | | Truncated

|-| Microsoft Excel| | | | Floored

|-| Minitab| | | | Floored

|-| rowspan="2" | Modula-2| | | | Floored|-| | | | Truncated

|-| MUMPS| | | | Floored

|-| rowspan="2" | Netwide Assembler (NASM, NASMX)|, (unsigned)| | | |-| (signed)| | | Implementation-defined[35]

|-| Nim| | | | Truncated

|-| Oberon| | | | Floored-like

|-| Objective-C| | | | Truncated (same as C99)

|-| Object Pascal, Delphi| | | | Truncated

|-| rowspan="2" | OCaml| | | | Truncated[36] |-| | | | Truncated[37]

|-| Occam| | | | Truncated

|-| Pascal (ISO-7185 and -10206)| | | | Euclidean-like

|-| rowspan="2" | Perl| | | | Floored|-| | | | Truncated

|-| rowspan="2" | Phix| | | | Floored|-| | | | Truncated

|-| rowspan="2" | PHP| | | | Truncated[38] |-| | | | Truncated[39]

|-| PIC BASIC Pro| | | | Truncated

|-| PL/I| | | | Floored (ANSI PL/I)

|-| PowerShell| | | | Truncated

|-| Programming Code (PRC)| | | | Undefined

|-| Progress| | | | Truncated

|-| rowspan="2"| Prolog (ISO 1995)| | | | Floored|-| | | | Truncated

|-| PureBasic|, | | | Truncated

|-| PureScript| | | | Euclidean[40]

|-| rowspan="2" | Pure Data| | | | Truncated (same as C)|-| | | | Floored

|-| rowspan="3" | Python| | | | Floored|-| | | | Truncated|-| | | | Rounded

|-| Q#| | | | Truncated[41]

|-| R| | | | Floored[42]

|-| rowspan="2" |Racket| | | | Floored|-| | | | Truncated

|-| Raku| | | | Floored

|-| RealBasic| | | | Truncated

|-| Reason| | | | Truncated

|-| Rexx| | | | Truncated

|-| RPG| | | | Truncated

|-| rowspan="2" | Ruby|, | | | Floored|-| | | | Truncated

|-| rowspan="2" | Rust| | | | Truncated|-| | | | Euclidean[43]

|-| SAS| | | | Truncated

|-| Scala| | | | Truncated

|-| rowspan="2" | Scheme| | | | Floored|-| | | | Truncated

|-| rowspan="4" | Scheme R6RS| | | | Euclidean[44] |-| | | | Rounded[44] |-| | | | Euclidean|-| | | | Rounded

|-| Scratch| | | | Floored

|-| rowspan="2" | Seed7| | | | Floored|-| | | | Truncated

|-| rowspan="2" | SenseTalk| | | | Floored|-| | | | Truncated

|-| (POSIX) (includes bash, mksh, &c.)| | | | Truncated (same as C)[45]

|-| rowspan="2" | Smalltalk| | | | Floored|-| | | | Truncated

|-| Snap!| | | | Floored

|-| Spin| | | | Floored

|-| Solidity| | | | Floored

|-| SQL | | | | Truncated

|-| SQL | | | | Truncated

|-| rowspan="3" | Standard ML| | | | Floored|-| | | | Truncated|-| | | | Truncated

|-| Stata| | | | Euclidean

|-| rowspan="3" | Swift| | | | Truncated[46] |-| | | | Rounded[47] |-| | | | Truncated[48]

|-| rowspan="2" | Tcl| | | | Floored|-| | | | Truncated (as C)

|-| tcsh| | | | Truncated

|-| Torque| | | | Truncated

|-| Turing| | | | Floored

|-| Verilog (2001)| | | | Truncated

|-| rowspan="2" | VHDL| | | | Floored|-| | | | Truncated

|-| VimL| | | | Truncated

|-| Visual Basic| | | | Truncated

|-| rowspan="2" | WebAssembly|, (unsigned)| | | [49] |-|, (signed)| | | Truncated

|-| x86 assembly| | | | Truncated

|-| rowspan="2" | XBase++| | | | Truncated|-| | | | Floored

|-| Zig|,, | | | Truncated[50]

|-| 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 modulo to lie not between 0 and, but between some number and . In that case, 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 . We thus have the following definition:[51] just in case 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}dn=a-n\left\lfloor

a-d
n

\right\rfloor.

To see this, let x = a - n \left\lfloor\frac\right\rfloor. We first show that . It is in general true that for all integers ; thus, this is true also in the particular case when b = -\!\left\lfloor\frac\right\rfloor; but that means that x \bmod n = \left(a - n \left\lfloor\frac\right\rfloor\right)\! \bmod n = a \bmod n, which is what we wanted to prove. It remains to be shown that . Let and be the integers such that with (see Euclidean division). Then \left\lfloor\frac\right\rfloor = k, thus x = a - n \left\lfloor\frac\right\rfloor = a - n k = d +r. Now take and add to both sides, obtaining . But we've seen that, so we are done.

The modulo with offset is implemented in Mathematica as &thinsp;.[51]

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:

/* Euclidean and Floored divmod, in the style of C's ldiv */typedef struct ldiv_t;

/* Euclidean division */inline ldiv_t ldivE(long numer, long denom)

/* Floored division */inline ldiv_t ldivF(long numer, long denom)

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

External links

Notes and References

  1. Web site: Weisstein. Eric W.. Congruence. 2020-08-27. Wolfram MathWorld . en.
  2. Web site: Caldwell. Chris. residue. August 27, 2020. Prime Glossary.
  3. Web site: Peterson . Doctor . Mod Function and Negative Numbers . Math Forum - Ask Dr. Math . 22 October 2019 . 5 July 2001. https://web.archive.org/web/20191022160922/http://mathforum.org/library/drmath/view/52343.html . 2019-10-22 .
  4. Web site: Adam . Horvath . Faster division and modulo operation - the power of two . July 5, 2012.
  5. Book: ISO/IEC 8652:2012 - Information technology — Programming languages — Ada. ISO, IEC. 2012. sec. 4.5.5 Multiplying Operators.
  6. Book: ISO/IEC 9899:1990: Programming languages – C . . 1990 . sec. 7.5.6.4 . The function returns the value, for some integer such that, if is nonzero, the result has the same sign as and magnitude less than the magnitude of ..
  7. Web site: dotnet-bot . Math.IEEERemainder(Double, Double) Method (System) . 2022-10-04 . Microsoft Learn . en-us.
  8. Web site: clojure.core - Clojure v1.10.3 API documentation . 2022-03-16 . clojure.github.io.
  9. Web site: clojure.core - Clojure v1.10.3 API documentation . 2022-03-16 . clojure.github.io.
  10. Book: ISO/IEC 1989:2023 – Programming language COBOL. ISO/IEC JTC 1/SC 22/WG 4. ISO. January 2023. subscription.
  11. http://coffeescript.org/#operators CoffeeScript operators
  12. Book: ISO/IEC JTC 1/SC 22. February 2012. ISO/IEC 23271:2012 — Information technology — Common Language Infrastructure (CLI). ISO. §§ III.3.55–56.
  13. Web site: Expressions - D Programming Language. 2021-06-01. dlang.org.
  14. Web site: operator % method - num class - dart:core library - Dart API. 2021-06-01. api.dart.dev.
  15. Web site: remainder method - num class - dart:core library - Dart API. 2021-06-01. api.dart.dev.
  16. Web site: Kernel — Elixir v1.11.3. 2021-01-28. hexdocs.pm.
  17. Web site: Integer — Elixir v1.11.3. 2021-01-28. hexdocs.pm.
  18. Web site: Basics - core 1.0.5 . 2022-03-16 . package.elm-lang.org.
  19. Web site: Basics - core 1.0.5 . 2022-03-16 . package.elm-lang.org.
  20. Web site: Erlang -- math. 2021-06-01. erlang.org.
  21. Book: [[ANSI]]. Programming Languages — Full BASIC. 28 January 1987. American National Standards Institute. New York. § 5.4.4. X modulo Y, i.e., X-Y*INT(X/Y)..
  22. Book: [[ANSI]]. Programming Languages — Full BASIC. 28 January 1987. American National Standards Institute. New York. § 5.4.4. "The remainder function, i.e., X-Y*IP(X/Y).".
  23. Web site: GLSL Language Specification, Version 4.50.7. section 5.9 Expressions. If both operands are non-negative, then the remainder is non-negative. Results are undefined if one or both operands are negative..
  24. Web site: GLSL Language Specification, Version 4.50.7. section 8.3 Common Functions.
  25. Web site: The Go Programming Language Specification - The Go Programming Language . 2022-02-28 . go.dev.
  26. Web site: math package - math - pkg.go.dev . 2022-02-28 . pkg.go.dev.
  27. Web site: big package - math/big - pkg.go.dev . 2022-02-28 . pkg.go.dev.
  28. Web site: big package - math/big - pkg.go.dev . 2024-04-12 . pkg.go.dev.
  29. Web site: 6 Predefined Types and Classes . 2022-05-22 . www.haskell.org.
  30. Web site: Operators . . . 2021-07-19 . 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..
  31. Web site: Mathematics · The Julia Language. 2021-11-20. docs.julialang.org.
  32. Web site: Mathematics · The Julia Language. 2021-11-20. docs.julialang.org.
  33. Web site: rem - Kotlin Programming Language. 2021-05-05. Kotlin. en.
  34. Web site: mod - Kotlin Programming Language. 2021-05-05. Kotlin. en.
  35. Web site: Chapter 3: The NASM Language . NASM - The Netwide Assembler version 2.15.05.
  36. Web site: OCaml library : Stdlib. 2022-02-19. ocaml.org.
  37. Web site: OCaml library : Stdlib. 2022-02-19. ocaml.org.
  38. Web site: PHP: Arithmetic Operators - Manual. 2021-11-20. www.php.net.
  39. Web site: PHP: fmod - Manual. 2021-11-20. www.php.net.
  40. Web site: EuclideanRing.
  41. Web site: Expressions. QuantumWriter. docs.microsoft.com. en-us. 2018-07-11.
  42. Web site: R: Arithmetic Operators . 2022-12-24 . search.r-project.org.
  43. Web site: F32 - Rust.
  44. http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_sec_11.7.3.1 r6rs.org
  45. Web site: Shell Command Language. 2021-02-05. pubs.opengroup.org.
  46. Web site: Apple Developer Documentation. 2021-11-20. developer.apple.com.
  47. Web site: Apple Developer Documentation. 2021-11-20. developer.apple.com.
  48. Web site: Apple Developer Documentation. 2021-11-20. developer.apple.com.
  49. Web site: Andreas. Rossberg. 19 April 2022. WebAssembly Core Specification: Version 2.0. World Wide Web Consortium. § 4.3.2 Integer Operations.
  50. Web site: Zig Documentation . 2022-12-18 . Zig Programming Language.
  51. Web site: Mod . . 2020 . Wolfram Language & System Documentation Center . . April 8, 2020 .