Modulo operation

From Wikipedia, the free encyclopedia
Jump to: navigation, search
Quotient (red) and remainder (green) functions using different algorithms.

In computing, the modulo operation finds the remainder of division of one number by another.

Given two positive numbers, a (the dividend) and n (the divisor), a modulo n (abbreviated as a mod n) can be thought of as the remainder, on division of a by n. For instance, the expression "7 mod 3" would evaluate to 1 because after dividing 7 by 3 the subtraction of 6 from 7 leaves 1, while "9 mod 3" would evaluate to 0 because the division of 9 by 3 is even, there is nothing to subtract from 9 after multiplying 3 times 3. (Notice that doing the division with a calculator won't show you the result referred to here by this operation.) When either a or n are negative, this naive definition breaks down and many programming languages differ in how these values are defined. Although typically performed with a and n both being integers, many computing systems allow other types of numeric operands. See modular arithmetic for an older and related convention applied in number theory.

Contents

[edit] Remainder calculation for the modulo operation

Integer modulo operators in various programming languages
Language Operator Result has the same sign as
ActionScript % Dividend
Ada mod Divisor
rem Dividend
ASP Mod Not defined
ALGOL-68 Always positive
AppleScript mod Dividend
BASIC Mod Not defined
bc % Dividend
bash % Dividend
C (ISO 1990) % Implementation defined
C (ISO 1999) % Dividend
C++ % Implementation defined[1]
C# % Dividend
CLARION % Dividend
Clojure mod Divisor
ColdFusion % Dividend
Common Lisp mod Divisor
rem Dividend
D % Dividend[2]
Eiffel \\ Dividend
Erlang rem Dividend
Euphoria mod Divisor
remainder Dividend
FileMaker Mod Divisor
Fortran mod Dividend
modulo Divisor
GML (Game Maker) mod Dividend
Go % Dividend
Haskell mod Divisor
rem Dividend
J |~ Divisor
Java % Dividend
JavaScript % Dividend
Just Basic MOD Dividend
Lua % Divisor
Liberty Basic MOD Dividend
MathCad mod(x,y) Divisor
Maple (software) e mod m Dividend
Mathematica Mod Divisor
Microsoft Excel =MOD() Divisor
MATLAB mod Divisor
rem Dividend
Oberon MOD Divisor
Objective Caml mod Dividend
Occam \ Dividend
Pascal (Delphi) mod Dividend
Perl % Divisor[1]
PHP % Dividend
PL/I mod Divisor (ANSI PL/I)
PowerBuilder mod(x,y)  ?
Prolog (ISO 1995) mod Divisor
rem Dividend
Python % Divisor
RealBasic MOD Dividend
R %% Divisor
RPG %REM Dividend
Ruby % Divisor
Scheme modulo Divisor
remainder Dividend
Scheme R6RS[2] mod Always Nonnegative (Euclidean)
mod0 Closest to zero
SenseTalk modulo Divisor
rem Dividend
Smalltalk \\ Divisor
SQL (SQL:1999) mod(x,y) Dividend
Standard ML mod Divisor
Int.rem Dividend
Tcl % Divisor
Torque Game Engine % Dividend
TI-BASIC fPart(x/y)*y Dividend
Turing (programming language) mod Divisor
Verilog (2001) % Dividend
VHDL mod Divisor
rem Dividend
Visual Basic Mod Dividend
x86 Assembly IDIV Dividend
Floating-point modulo operators in various programming languages
Language Operator Result has the same sign as
C (ISO 1990) fmod  ?
C (ISO 1999) fmod Dividend
remainder Closest to zero
C++ std::fmod  ?
C# % Dividend
Common Lisp mod Divisor
rem Dividend
Go math.Fmod Dividend
Haskell (GHC) Data.Fixed.mod' Divisor
Java % Dividend
JavaScript % Dividend
Objective Caml mod_float Dividend
Perl POSIX::fmod Dividend
PHP fmod Dividend
Python % Divisor
math.fmod Dividend
Ruby % Divisor
Scheme R6RS flmod Always Nonnegative (Euclidean)
flmod0 Closest to zero
Standard ML Real.rem Dividend

There are various ways of defining a remainder, and computers and calculators have various ways of storing and representing numbers, so what exactly constitutes the result of a modulo operation depends on the programming language and/or the underlying hardware.

In nearly all computing systems, the quotient q and the remainder r satisfy

q \in \mathbb{Z}
a = n \times q + r\,
\left| r \right| < \left| n \right|

This means there are two possible choices for the remainder, one negative and the other positive, and there are also two possible choices for the quotient. Usually, in number theory, the positive remainder is always chosen, but programming languages choose depending on the language and the signs of a and n.[3] However, Pascal and Algol68 do not satisfy these conditions for negative divisors, and some programming languages, such as C89, don't even define a result if either of n or a is negative. See the table for details. a modulo 0 is undefined in the majority of systems, although some do define it to be a.

Many implementations use truncated division where the quotient is defined by truncation q = trunc(a/n) and the remainder by r=a-n q. With this definition the quotient is rounded towards zero and the remainder has the same sign as the dividend.

Knuth[3] described floored division where the quotient is defined by the floor function q=floor(a/n) and the remainder r is

r = a - n \left\lfloor {a \over n} \right\rfloor.

Here the quotient rounds towards negative infinity and the remainder has the same sign as the divisor.

Raymond T. Boute[4] introduces the Euclidean definition which is consistent with the division algorithm. Let q be the integer quotient of a and n, then:

q \in \mathbb{Z}
a = n \times q + r\,
0 \leq r < |n|.

Two corollaries are that

n > 0 \Rightarrow q = \left\lfloor \frac{a}{n} \right\rfloor
n < 0 \Rightarrow q = \left\lceil \frac{a}{n} \right\rceil.

As described by Leijen,[5]

Boute argues that Euclidean division is superior to the other ones in terms of regularity and useful mathematical properties, although floored division, promoted by Knuth, is also a good definition. Despite its widespread use, truncated division is shown to be inferior to the other definitions.

Common Lisp also defines round- and ceiling-division where the quotient is given by q=round(a/n), q=ceil(a/n). IEEE 754 defines a remainder function where the quotient is a/n rounded according to the round to nearest convention.

[edit] Common pitfalls

When the result of a modulo operation has the sign of the dividend, it can sometimes lead to surprising mistakes:

For example, to test whether an integer is odd, one might be inclined to test whether 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 n (the dividend) is negative and odd, n % 2 returns -1, and the function returns false.

One correct alternative is to test that it is not 0 (because remainder 0 is the same regardless of the signs):

bool is_odd(int n) {
    return n % 2 != 0;
}

[edit] Modulo operation expression

Some calculators have a mod() function button, and many programming languages have a mod() function or similar, expressed as mod(a, n), for example. Some also support expressions that use "%", "mod", or "Mod" as a modulo or remainder operator, such as

a % n

or

a mod n

or equivalent, for environments lacking a mod() function

a - (n * int(a/n))

[edit] Performance issues

Modulo operations might be implemented such that a division with a remainder is calculated each time. For special cases, there are faster alternatives on some hardware. For example, the modulo of powers of 2 can alternatively be expressed as a bitwise AND operation:

x % 2n == x & (2n - 1).

Examples (assuming x is an integer):

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.

Optimizing C compilers generally recognize expressions of the form expression % constant where constant is a power of two and automatically implement them as expression & (constant-1). This can allow the programmer to write clearer code without compromising performance. (Note: This will not work for the languages whose modulo have the sign of the dividend (including C), because if the dividend is negative, the modulo will be negative; however, expression & (constant-1) will always produce a positive result. So special treatment has to be made when the dividend is negative.)

In some compilers, the modulo operation is implemented as mod(a, n) = a - n * floor(a / n). When performing both modulo and division on the same numbers, one can get the same result somewhat more efficiently by avoiding the actual modulo operator, and using the formula above on the result, avoiding an additional division operation.

[edit] See also

[edit] Notes

[edit] References

  1. ^ ISO/IEC 14882:2003 : Programming languages -- C++. 5.6.4: ISO, IEC. 2003 . "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".
  2. ^ "Expressions". D Programming Language 2.0. Digital Mars. http://www.digitalmars.com/d/2.0/expression.html#MulExpression. Retrieved 29 July 2010. 
  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 Transactions on Programming Languages and Systems (TOPLAS) (ACM Press (New York, NY, USA)) 14 (2): 127 – 144. doi:10.1145/128861.128862. http://portal.acm.org/citation.cfm?id=128862&coll=portal&dl=ACM. 
  5. ^ Leijen, Daan (December 3, 2001). "Division and Modulus for Computer Scientists" (PDF). http://www.cs.uu.nl/~daan/download/papers/divmodnote.pdf. Retrieved 2006-08-27. 

[edit] External links

Personal tools
Namespaces
Variants
Actions
Navigation
Interaction
Toolbox
Print/export
Languages