Product Code Database
Example Keywords: retro games -photography $65-153
   » » Wiki: Modulo
Tag Wiki 'Modulo'.
Tag

In and , the modulo operation returns the 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 and , modulo (often abbreviated as ) is the remainder of the Euclidean division of by , where is the dividend and is the .

For example, the expression "5 mod 2" evaluates to 1, because 5 divided by 2 has a 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 , 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.

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 , 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 and the remainder of divided by n \neq 0 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). Some systems leave modulo 0 undefined, though others define it as .

< |n|. (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}
\\ &= \text{sgn}(n) \cdot \left( \frac{a}
- \frac{r}
\right) \\ &= \text{sgn}(n) \cdot \left\lfloor \frac{a}{\left|n\right|} \right\rfloor \end{align} where is the , \lfloor\,\rfloor is the (rounding down), and \frac{a}
\in \mathbb{Q}, \frac{r}
\in \mathbb{Q} are .

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 < 0 \\
     
\end{cases} where \lceil\,\rceil is the (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

|

Common Lisp and IEEE 754 use rounded division, for which the quotient is defined by q = \operatorname{round}\left(\frac{a}{n}\right) where is the (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)

|

Common Lisp also uses ceiling division, for which the quotient is defined by q = \left\lceil\frac{a}{n}\right\rceil where ⌈⌉ is the (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
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) {

   return n % 2 == 1;
     
}

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

   return n % 2 != 0;
     
}

Or with the binary arithmetic: 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 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.

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 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 proofs, such as the Diffie–Hellman key exchange. The properties involving multiplication, division, and exponentiation generally require that and are integers.
  • Identity:
    • .
    • for all positive integer values of .
    • If is a which is not a of , then , due to Fermat's little theorem.
  • Inverse:
    • .
    • denotes the modular multiplicative inverse, which is defined if and only if and are , which is the case when the left hand side is defined: .
  • Distributive:
    • .
    • .
  • Division (definition): , when the right hand side is defined (that is when and are ), and undefined otherwise.
  • Inverse multiplication: .


In programming languages
Euclidean

Truncated

Ada Floored
Truncated

ALGOL 68, , , , '''mod''' Euclidean

Truncated

APL<nowiki></nowiki> Floored

Truncated

Truncated

Truncated (same as in C)

Varies by implementation

bc Truncated

CC++, Truncated
(C) (C++) Truncated
(C) (C++) Rounded

C# Truncated
Rounded

Clarion Truncated

Clean Truncated

Floored
Truncated

Floored
Truncated

Truncated
Floored CoffeeScript operators

, Truncated

Common Intermediate Language(signed) Truncated
(unsigned)

Floored
Truncated

Crystal, Floored
Truncated

Floored
Truncated

D Truncated

Dart Euclidean
Truncated

Eiffel Truncated

Elixir Truncated
Floored

Elm Floored
Truncated

Erlang Truncated
Truncated (same as C)

Euphoria Truncated
Floored

F# Truncated (same as C#)
Rounded

Factor Truncated
Euclidean

Floored

Forth Implementation defined
Floored
Truncated

Truncated
Floored

Frink Floored

Floored
Truncated

Undefined
Floored

(GML), Truncated

GDScript (Godot) Truncated
Euclidean
Truncated
Euclidean

Go Truncated
Truncated
Euclidean
Truncated
Truncated

Haskell Floored
Truncated
(GHC) Floored

Truncated

Undefined

J<nowiki></nowiki> Floored

Java Truncated
Floored

Truncated

Julia Floored
, Truncated

Kotlin, Truncated
Floored

Truncated (same as POSIX )
Truncated

Truncated

Floored

Logo Floored
Truncated

Lua 5 Floored

Lua 4 Truncated

Truncated

Floored

Maple(by default), Euclidean
Rounded
Rounded

Floored

Floored
Truncated

Maxima Floored
Truncated

Maya Embedded Language Truncated

Floored

Floored

Modula-2 Floored
Truncated

Floored

Netwide Assembler (NASM, NASMX), (unsigned)
(signed) Implementation-defined

Nim Truncated

Oberon Floored-like

Truncated (same as C99)

, Delphi Truncated

Truncated
Truncated

Occam Truncated

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

Floored
Truncated

Truncated
Truncated

PIC Pro Truncated

PL/I Floored (ANSI PL/I)

Truncated

Programming Code (PRC) Undefined

Progress Truncated

( ISO 1995) Floored
Truncated

, Truncated

Euclidean

Truncated (same as C)
Floored

Python Floored
Truncated
Rounded

Truncated

R Floored

Racket Floored
Truncated

Raku Floored

Truncated

Reason Truncated

Truncated

RPG Truncated

Ruby, Floored
Truncated

Rust Truncated
Euclidean

Truncated

Scala Truncated

Scheme Floored
Truncated

Scheme R6RS Euclidean r6rs.org
Rounded
Euclidean
Rounded

Scratch Floored

Seed7 Floored
Truncated

Floored
Truncated

(includes bash, , &c.) Truncated (same as C)

Floored
Truncated

Snap! Floored

Spin Floored

Truncated

() Truncated

() Truncated

Floored
Truncated
Truncated

Euclidean

Swift Truncated
Rounded
Truncated

Tcl Floored
Truncated (same as C)

Truncated

Torque Truncated

Turing Floored

(2001) Truncated

Floored
Truncated

Truncated

Visual Basic Truncated

, (unsigned)
, (signed) Truncated

x86 assembly Truncated

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 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: 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}_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 ; 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 . Let and be the integers such that with (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 and add to both sides, obtaining . But we've seen that , so we are done.

The modulo with offset is implemented in 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:

/* 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.


See also
  • Modulo (disambiguation) – many uses of the word modulo, all of which grew out of Carl F. Gauss' approach to modular arithmetic in 1801.
  • Modulo (mathematics), general use of the term in mathematics
  • Modular exponentiation
  • Turn (angle)


Notes

External links

Page 1 of 1
1
Page 1 of 1
1

Account

Social:
Pages:  ..   .. 
Items:  .. 

Navigation

General: Atom Feed Atom Feed  .. 
Help:  ..   .. 
Category:  ..   .. 
Media:  ..   .. 
Posts:  ..   ..   .. 

Statistics

Page:  .. 
Summary:  .. 
1 Tags
10/10 Page Rank
5 Page Refs
1s Time