HOME

TheInfoList



OR:

In
computing Computing is any goal-oriented activity requiring, benefiting from, or creating computing machinery. It includes the study and experimentation of algorithmic processes, and development of both hardware and software. Computing has scientific, e ...
, the modulo operation returns the
remainder In mathematics, the remainder is the amount "left over" after performing some computation. In arithmetic, the remainder is the integer "left over" after dividing one integer by another to produce an integer quotient (integer division). In algebr ...
or signed remainder of a
division Division or divider may refer to: Mathematics *Division (mathematics), the inverse of multiplication *Division algorithm, a method for computing the result of mathematical division Military *Division (military), a formation typically consisting ...
, 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 In arithmetic, Euclidean division – or division with remainder – is the process of dividing one integer (the dividend) by another (the divisor), in a way that produces an integer quotient and a natural number remainder strictly smaller than ...
of by , where is the
dividend A dividend is a distribution of profits by a corporation to its shareholders. When a corporation earns a profit or surplus, it is able to pay a portion of the profit as a dividend to shareholders. Any amount not distributed is taken to be re-in ...
and is the
divisor In mathematics, a divisor of an integer n, also called a factor of n, is an integer m that may be multiplied by some integer to produce n. In this case, one also says that n is a multiple of m. An integer n is divisible or evenly divisible by ...
. For example, the expression "5 mod 2" would evaluate to 1, because 5 divided by 2 has a
quotient In arithmetic, a quotient (from lat, quotiens 'how many times', pronounced ) is a quantity produced by the division of two numbers. The quotient has widespread use throughout mathematics, and is commonly referred to as the integer part of 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; there is nothing to subtract from 9 after multiplying 3 times 3. Although typically performed with and both being
integer An integer is the number zero (), a positive natural number (, , , etc.) or a negative integer with a minus sign (−1, −2, −3, etc.). The negative numbers are the additive inverses of the corresponding positive numbers. In the language ...
s, many computing systems now allow other types of numeric operands. The range of values for an integer modulo operation of is 0 to inclusive ( mod 1 is always 0; is undefined, possibly resulting in a
division by zero In mathematics, division by zero is division (mathematics), division where the divisor (denominator) is 0, zero. Such a division can be formally expression (mathematics), expressed as \tfrac, where is the dividend (numerator). In ordinary ari ...
error in some
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
s). See
Modular arithmetic In mathematics, modular arithmetic is a system of arithmetic for integers, where numbers "wrap around" when reaching a certain value, called the modulus. The modern approach to modular arithmetic was developed by Carl Friedrich Gauss in his book ...
for an older and related convention applied in
number theory Number theory (or arithmetic or higher arithmetic in older usage) is a branch of pure mathematics devoted primarily to the study of the integers and arithmetic function, integer-valued functions. German mathematician Carl Friedrich Gauss (1777â ...
. When exactly one of or is negative, the naive definition breaks down, and programming languages differ in how these values are defined.


Variants of the definition

In
mathematics Mathematics is an area of knowledge that includes the topics of numbers, formulas and related structures, shapes and the spaces in which they are contained, and quantities and their changes. These topics are represented in modern mathematics ...
, the result of the
modulo 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 t ...
operation is an
equivalence class In mathematics, when the elements of some set S have a notion of equivalence (formalized as an equivalence relation), then one may naturally split the set S into equivalence classes. These equivalence classes are constructed so that elements a ...
, and any member of the class may be chosen as
representative Representative may refer to: Politics * Representative democracy, type of democracy in which elected officials represent a group of people * House of Representatives, legislative body in various countries or sub-national entities * Legislator, som ...
; 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 In arithmetic, Euclidean division – or division with remainder – is the process of dividing one integer (the dividend) by another (the divisor), in a way that produces an integer quotient and a natural number remainder strictly smaller than ...
). 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 A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
or the underlying hardware. In nearly all computing systems, the quotient and the remainder of divided by satisfy the following conditions: : However, 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, and two possible choices for the quotient occur. 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 Pascal, Pascal's or PASCAL may refer to: People and fictional characters * Pascal (given name), including a list of people with the name * Pascal (surname), including a list of people and fictional characters with the name ** Blaise Pascal, Fren ...
and
ALGOL 68 ALGOL 68 (short for ''Algorithmic Language 1968'') is an imperative programming language that was conceived as a successor to the ALGOL 60 programming language, designed with the goal of a much wider scope of application and more rigorously de ...
, 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 . As described by Leijen, However, truncated division satisfies the identity ()/b = = a/().


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 Odd means unpaired, occasional, strange or unusual, or a person who is viewed as eccentric. Odd may also refer to: Acronym * ODD (Text Encoding Initiative) ("One Document Does it all"), an abstracted literate-programming format for describing X ...
, 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 A power of two is a number of the form where is an integer, that is, the result of exponentiation with number two as the base and integer  as the exponent. In a context where only integers are considered, is restricted to non-negative ...
can alternatively be expressed as a bitwise AND operation (assuming 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 optimization In computing, an optimizing compiler is a compiler that tries to minimize or maximize some attributes of an executable computer program. Common requirements are to minimize a program's execution time, memory footprint, storage size, and power con ...
s 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 Unsigned can refer to: * An unsigned artist is a musical artist or group not attached or signed to a record label ** Unsigned Music Awards, ceremony noting achievements of unsigned artists ** Unsigned band web, online community * Similarly, the c ...
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 < 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 Cryptography, or cryptology (from grc, , translit=kryptós "hidden, secret"; and ''graphein'', "to write", or ''-logia'', "study", respectively), is the practice and study of techniques for secure communication in the presence of adver ...
proofs, such as the
Diffie–Hellman key exchange Diffie–Hellman key exchangeSynonyms of Diffie–Hellman key exchange include: * Diffie–Hellman–Merkle key exchange * Diffie–Hellman key agreement * Diffie–Hellman key establishment * Diffie–Hellman key negotiation * Exponential key exc ...
. Some of these properties require that and are integers. * Identity: ** . ** for all positive integer values of . ** If is a
prime number A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers. A natural number greater than 1 that is not prime is called a composite number. For example, 5 is prime because the only ways ...
which is not a
divisor In mathematics, a divisor of an integer n, also called a factor of n, is an integer m that may be multiplied by some integer to produce n. In this case, one also says that n is a multiple of m. An integer n is divisible or evenly divisible by ...
of , then , due to
Fermat's little theorem Fermat's little theorem states that if ''p'' is a prime number, then for any integer ''a'', the number a^p - a is an integer multiple of ''p''. In the notation of modular arithmetic, this is expressed as : a^p \equiv a \pmod p. For example, if = ...
. * Inverse: ** . ** denotes the
modular multiplicative inverse In mathematics, particularly in the area of arithmetic, a modular multiplicative inverse of an integer is an integer such that the product is congruent to 1 with respect to the modulus .. In the standard notation of modular arithmetic this congr ...
, which is defined
if and only if In logic and related fields such as mathematics and philosophy, "if and only if" (shortened as "iff") is a biconditional logical connective between statements, where either both statements are true or both are false. The connective is bicondi ...
and are
relatively prime In mathematics, two integers and are coprime, relatively prime or mutually prime if the only positive integer that is a divisor of both of them is 1. Consequently, any prime number that divides does not divide , and vice versa. This is equivale ...
, 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
coprime In mathematics, two integers and are coprime, relatively prime or mutually prime if the only positive integer that is a divisor of both of them is 1. Consequently, any prime number that divides does not divide , and vice versa. This is equivale ...
), and undefined otherwise. * Inverse multiplication: .


In programming languages

In addition, many computer systems provide a functionality, which produces the quotient and the remainder at the same time. Examples include the
x86 architecture x86 (also known as 80x86 or the 8086 family) is a family of complex instruction set computer (CISC) instruction set architectures initially developed by Intel based on the Intel 8086 microprocessor and its 8088 variant. The 8086 was introd ...
's instruction, the C programming language's function, and
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
'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.'' 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 In mathematics and computer science, the floor function is the function that takes as input a real number , and gives as output the greatest integer less than or equal to , denoted or . Similarly, the ceiling function maps to the least int ...
as follows: ::a \operatorname_d n = a - n \left\lfloor\frac\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 In arithmetic, Euclidean division – or division with remainder – is the process of dividing one integer (the dividend) by another (the divisor), in a way that produces an integer quotient and a natural number remainder strictly smaller than ...
). 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 Wolfram Mathematica is a software system with built-in libraries for several areas of technical computing that allow machine learning, statistics, symbolic computation, data manipulation, network analysis, time series analysis, NLP, optimizat ...
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 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

* Modulo (disambiguation) and
modulo (jargon) In mathematics, the term ''modulo'' ("with respect to a modulus of", the Latin ablative of '' modulus'' which itself means "a small measure") is often used to assert that two distinct mathematical objects can be regarded as equivalent—if their ...
– many uses of the word ''modulo'', all of which grew out of
Carl F. Gauss Johann Carl Friedrich Gauss (; german: Gauß ; la, Carolus Fridericus Gauss; 30 April 177723 February 1855) was a German mathematician and physicist who made significant contributions to many fields in mathematics and science. Sometimes refer ...
's introduction of ''
modular arithmetic In mathematics, modular arithmetic is a system of arithmetic for integers, where numbers "wrap around" when reaching a certain value, called the modulus. The modern approach to modular arithmetic was developed by Carl Friedrich Gauss in his book ...
'' in 1801. *
Modulo (mathematics) In mathematics, the term ''modulo'' ("with respect to a modulus of", the Latin ablative of '' modulus'' which itself means "a small measure") is often used to assert that two distinct mathematical objects can be regarded as equivalent—if thei ...
, general use of the term in mathematics *
Modular exponentiation Modular exponentiation is exponentiation performed over a modulus. It is useful in computer science, especially in the field of public-key cryptography, where it is used in both Diffie-Hellman Key Exchange and RSA public/private keys. Modul ...
*
Turn (unit) A turn is a unit of plane angle measurement equal to  radians, 360  degrees or 400 gradians. Subdivisions of a turn include half-turns, quarter-turns, centiturns, milliturns, etc. The closely related terms ''cycle'' and ''revo ...


Notes


References


External links


Modulorama
animation of a cyclic representation of multiplication tables (explanation in French) {{DEFAULTSORT:Modulo operation Computer arithmetic Articles with example C++ code Operators (programming) Modular arithmetic Operations on numbers de:Division mit Rest#Modulo