Jump to content

Modulo: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
Crashie (talk | contribs)
Common pitfalls: Fixed example code. The expression (1 || -1) evaluates to 1 so it will behave like the first example (the one that doesn't work)
Line 382: Line 382:
<source lang="cpp">
<source lang="cpp">
bool is_odd(int n) {
bool is_odd(int n) {
return n % 2 == ( 1 || -1 );
return n % 2 == 1 || n % 2 == -1;
}
}
</source>
</source>

Revision as of 12:00, 14 July 2013

Quotient (red) and remainder (green) functions using different algorithms

In computing, the modulo (sometimes called modulus) 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) is the remainder of the Euclidean division of a by n. For instance, the expression "5 mod 2" would evaluate to 1 because 5 divided by 2 leaves a quotient of 2 and a remainder of 1, while "9 mod 3" would evaluate to 0 because the division of 9 by 3 has a quotient of 3 and leaves a remainder of 0; 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, the quotient will be expressed as a decimal fraction.) When either a or n is negative, this naive definition breaks down and 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. The range of numbers for an integer modulo of n is 0 to n − 1. (n mod 1 is always 0; n mod 0 is undefined, possibly resulting in a "Division by zero" error in computer programming languages) See modular arithmetic for an older and related convention applied in number theory.

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
AMPL mod Dividend
APL | Divisor
AppleScript mod Dividend
BASIC Mod Not defined
bc % Dividend
bash % Dividend
C (ISO 1990) % Implementation defined
C (ISO 1999) % Dividend[1]
C++ (ISO 1998) % Implementation defined[2]
C++ (ISO 2011) % Dividend
C# % Dividend
CLARION % Dividend
Clojure mod Divisor
COBOL[1] FUNCTION MOD Divisor
ColdFusion %, MOD Dividend
Common Lisp mod Divisor
rem Dividend
D % Dividend[3]
Dart % Divisor
Eiffel \\ Dividend
Erlang rem Dividend
Euphoria mod Divisor
remainder Dividend
F# % Dividend
FileMaker Mod Divisor
Fortran mod Dividend
modulo Divisor
Frink mod Divisor
GML (Game Maker) mod Dividend
Go % Dividend
Haskell mod Divisor
rem Dividend
J |~ Divisor
Java % Dividend
JavaScript % Dividend
Lua 5 % Divisor
Lua 4 mod(x,y) Divisor
Liberty Basic MOD Dividend
MathCad mod(x,y) Divisor
Maple e mod m Always positive
Mathematica Mod Divisor
MATLAB mod Divisor
rem Dividend
Maxima mod Divisor
remainder Dividend
Maya Embedded Language fmod Always positive
Microsoft Excel =MOD() Divisor
Minitab MOD Divisor
MUMPS # Divisor
NASM NASMX % Unsigned Modulo Operator
%% Signed Modulo Operator
Oberon MOD Divisor[2]
OCaml mod Dividend
Occam \ Dividend
Pascal (Delphi) mod Dividend
Pascal (ISO-7185 and ISO-10206) mod Always positive
Perl % Divisor[3]
PHP % Dividend
PIC Basic Pro \\ Dividend
PL/I mod Divisor (ANSI PL/I)
PowerBuilder mod(x,y) ?
PowerShell % Dividend
Progress modulo Dividend
Prolog (ISO 1995) mod Divisor
rem Dividend
Python % Divisor
RealBasic MOD Dividend
R %% Divisor
REXX // Dividend
RPG %REM Dividend
Ruby %, modulo() Divisor
remainder() Dividend
Scala % Dividend
Scheme modulo Divisor
remainder Dividend
Scheme R6RS mod Always positive[4]
mod0 Closest to zero[4]
Seed7 mod Divisor
rem Dividend
SenseTalk modulo Divisor
rem Dividend
Smalltalk \\ Divisor
rem: Dividend
SQL (SQL:1999) mod(x,y) Dividend
Standard ML mod Divisor
Int.rem Dividend
Stata mod(x,y) Always positive
Tcl % Divisor
Torque Game Engine % Dividend
Turing 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++ (ISO 1998) std::fmod ?
C++ (ISO 2011) std::fmod Dividend
std::remainder Closest to zero
C# % Dividend
Common Lisp mod Divisor
rem Dividend
D % Dividend
F# % Dividend
Fortran mod Dividend
modulo Divisor
Go math.Fmod Dividend
Haskell (GHC) Data.Fixed.mod' Divisor
Java % Dividend
JavaScript % Dividend
OCaml mod_float Dividend
Perl POSIX::fmod Dividend
Perl6 % Divisor
PHP fmod Dividend
Python % Divisor
math.fmod Dividend
REXX // Dividend
Ruby %, modulo() Divisor
remainder() Dividend
Scheme R6RS flmod Always positive
flmod0 Closest to zero
Standard ML Real.rem Dividend

In mathematics the result of the modulo operation is 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 and/or the underlying hardware.

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

This means that, if the remainder is nonzero, 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.[4] Pascal and Algol68 give a positive remainder (or 0) even 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), in other words it is the first integer in the direction of 0 from the exact rational quotient, and the remainder by r=an q. Informally speaking the quotient is "rounded towards zero", and the remainder therefore has the same sign as the dividend.

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

Here the quotient is always rounded downwards (even if it is already negative) and the remainder has the same sign as the divisor.

Raymond T. Boute[6] introduces the Euclidean definition, which is the one in which the remainder is always positive or 0, and is therefore consistent with the division algorithm (see Euclidean division). This definition is marked as "Always positive" in the table. Let q be the integer quotient of a and n, then:

Two corollaries are that

or, equivalently,

As described by Leijen,[7]

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.

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;
}

Or, by understanding in the first place that for any odd number, the modulo remainder may be either 1 or -1:

bool is_odd(int n) {
    return n % 2 == 1 || n % 2 == -1;
}

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

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 a positive 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. [8]

Optimizing compilers may 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 can be negative.)

In some compilers, the modulo operation is implemented as mod(a, n) = a - n * floor(a / n). For example, mod(7, 3) = 7 - 3 * floor(7 / 3) = 7 - 3 * floor(2.33) = 7 - 3 * 2 = 7 - 6 = 1.

Equivalencies

Some modulo operations can be factored or expanded similar to other mathematical operations. This may be useful in cryptography proofs, such as the Diffie–Hellman key exchange.

  • Identity:
    • for all positive integer values of .
    • If is a prime number which is not a divisor of , then , due to Fermat's little theorem.
  • Inverse:
    • denotes the modular multiplicative inverse, which is defined if and only if and are relatively prime, which is the case when the left hand side is defined: .
  • Distributive:
  • Division (definition): , when the right hand side is defined. Not defined otherwise.
  • Inverse Multiplication:

Common misconceptions

It is a common mistake to believe that ; however this property is not true, for instance but .

Another common mistake is to forget the last in the above formulas. Using the same example ; however .

See also

Notes

  • ^ Perl usually uses arithmetic modulo operator that is machine-independent. See the Perl documentation for exceptions and examples.
  • ^ Mathematically, these two choices are but two of the infinite number of choices available for the inequality satisfied by a remainder.
  • ^ Divisor must be positive, otherwise not defined.
  • ^ As implemented in ACUCOBOL, Micro Focus COBOL, and possibly others.

References

  1. ^ open-std.org, section 6.5.5
  2. ^ "ISO/IEC 14882:2003 : Programming languages -- C++" (Document). 5.6.4: ISO, IEC. 2003.{{cite document}}: CS1 maint: location (link). "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".
  3. ^ "Expressions". D Programming Language 2.0. Digital Mars. Retrieved 29 July 2010.
  4. ^ a b r6rs.org
  5. ^ Knuth, Donald. E. (1972). The Art of Computer Programming. Addison-Wesley.
  6. ^ Boute, Raymond T. (April 1992). "The Euclidean definition of the functions div and mod". ACM Transactions on Programming Languages and Systems (TOPLAS). 14 (2). ACM Press (New York, NY, USA): 127–144. doi:10.1145/128861.128862.
  7. ^ Leijen, Daan (December 3, 2001). "Division and Modulus for Computer Scientists" (PDF). Retrieved 2006-08-27.
  8. ^ Horvath, Adam (July 5, 2012). "Faster division and modulo operation - the power of two".