Modulo: Difference between revisions
Kotlin supports % and rem operation for floating point arguments, proof: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-double/rem.html |
Hans Bauer (talk | contribs) Mod and rem work also for float |
||
Line 1,064: | Line 1,064: | ||
| <code>mod</code> |
| <code>mod</code> |
||
| {{yes}} |
| {{yes}} |
||
| {{ |
| {{yes}} |
||
| Floored |
| Floored |
||
|- |
|- |
||
| <code>rem</code> |
| <code>rem</code> |
||
| {{yes}} |
| {{yes}} |
||
| {{ |
| {{yes}} |
||
| Truncated |
| Truncated |
||
Revision as of 07:24, 28 February 2021
![](http://upload.wikimedia.org/wikipedia/commons/thumb/2/22/Divmod.svg/250px-Divmod.svg.png)
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 a and n, a modulo n (abbreviated as a mod n) is the remainder of the Euclidean division of a by n, where a is the dividend and n is the divisor.[1] The modulo operation is to be distinguished from the symbol mod, which refers to the modulus[2] (or divisor) one is operating from.
For example, the expression "5 mod 2" would evaluate 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 the division of 9 by 3 has a quotient of 3 and a remainder of 0; there is nothing to subtract from 9 after multiplying 3 times 3.
(Here, notice that doing division with a calculator will not show the result of the modulo operation, and that the quotient will be expressed as a decimal fraction if a non-zero remainder is involved.)
Although typically performed with a and n both being integers, many computing systems now allow other types of numeric operands. The range of numbers for an integer modulo of n is 0 to n − 1 inclusive (a mod 1 is always 0; a mod 0 is undefined, possibly resulting in a division by zero error in some programming languages). See modular arithmetic for an older and related convention applied in number theory.
When exactly one of a or n is negative, the naive 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).[3] 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 q and the remainder r of a divided by n satisfy the following conditions:
(1)
However, this still leaves a sign ambiguity if the remainder is nonzero: 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 a or n.[a] 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 n or a is negative (see the table under § In programming languages for details). a modulo 0 is undefined in most systems, although some do define it as a.
- Many implementations use truncated division, where the quotient is defined by truncation q = trunc(a/n) and thus according to equation (1) the remainder would have same sign as the dividend. The quotient is rounded towards zero: equal to the first integer in the direction of zero from the exact rational quotient.
- Donald Knuth[4] described floored division where the quotient is defined by the floor function q = ⌊a/n⌋ and thus according to equation (1) the remainder would have the same sign as the divisor. Due to the floor function, the quotient is always rounded downwards, even if it is already negative.
- Raymond T. Boute[5] describes the Euclidean definition in which the remainder is nonnegative always, 0 ≤ r, and is thus consistent with the Euclidean division algorithm. In this case,
or equivalently
where sgn is the sign function, and thus
- A round-division is where the quotient is round(a/n), i.e. rounded to the nearest integer. It is found in Common Lisp and IEEE 754 (see the round to nearest convention in IEEE-754). Thus, the sign of the remainder is chosen to be nearest to zero.
- Common Lisp also defines ceiling-division (remainder different sign from divisor) where the quotient is given by q = ⌈a/n⌉. Thus, the sign of the remainder is chosen to be different from that of the divisor.
As described by Leijen,
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.
— Daan Leijen, Division and Modulus for Computer Scientists[6]
However, truncated division satisfies the identity .[7]
Notation
Some calculators have a mod() function button, and many programming languages have a similar function, 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
.
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 (truncating 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 n (the dividend) is negative and odd, n 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;
}
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) {
return n % 2 == 1 || n % 2 == -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 x is a positive integer, or using a non-truncating definition):
x % 2n == x & (2n - 1)
Examples:
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]
Compiler optimizations may recognize expressions of the form expression % constant
where constant
is a power of two and automatically implement them as expression & (constant-1)
, 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 expression & (constant-1)
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.
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.
- Identity:
- (a mod n) mod n = a mod n.
- nx mod n = 0 for all positive integer values of x.
- If p is a prime number which is not a divisor of b, then abp−1 mod p = a mod p, due to Fermat's little theorem.
- Inverse:
- [(−a mod n) + (a mod n)] mod n = 0.
- b−1 mod n denotes the modular multiplicative inverse, which is defined if and only if b and n are relatively prime, which is the case when the left hand side is defined: [(b−1 mod n)(b mod n)] mod n = 1.
- Distributive:
- (a + b) mod n = [(a mod n) + (b mod n)] mod n.
- ab mod n = [(a mod n)(b mod n)] mod n.
- Division (definition): a/b mod n = [(a mod n)(b−1 mod n)] mod n, when the right hand side is defined (that is when b and n are coprime). Undefined otherwise.
- Inverse multiplication: [(ab mod n)(b−1 mod n)] mod n = a mod n.
In programming languages
Language | Operator | Integer | Floating-point | Definition |
---|---|---|---|---|
ABAP | MOD
|
Yes | Yes | Euclidean |
ActionScript | %
|
Yes | No | Truncated |
Ada | mod
|
Yes | No | Floored |
rem
|
Yes | No | Truncated | |
ALGOL 68 | ÷× , mod
|
Yes | No | Euclidean |
AMPL | mod
|
Yes | No | Truncated |
APL | | [b]
|
Yes | No | Floored |
AppleScript | mod
|
Yes | No | Truncated |
AutoLISP | (rem d n)
|
Yes | No | Truncated |
AWK | %
|
Yes | No | Truncated |
BASIC | Mod
|
Yes | No | Undefined |
bc | %
|
Yes | No | Truncated |
C (ISO 1990)
C++ (ISO 1998) |
%
|
Yes | No | Implementation-defined[9] |
div
|
Yes | No | Truncated | |
fmod (C), std::fmod (C++)
|
No | Yes | Truncated[10] | |
C (ISO 1999) | % , div
|
Yes | No | Truncated[11] |
fmod (C), std::fmod (C++)
|
No | Yes | Truncated | |
remainder (C), std::remainder (C++)
|
No | Yes | Rounded | |
C# | %
|
Yes | Yes | Truncated |
Clarion | %
|
Yes | No | Truncated |
Clean | rem
|
Yes | No | Truncated |
Clojure | mod
|
Yes | No | Floored |
rem
|
Yes | No | Truncated | |
COBOL | FUNCTION MOD
|
Yes | No | Floored[c] |
CoffeeScript | %
|
Yes | No | Truncated |
%%
|
Yes | No | Floored[12] | |
ColdFusion | % , MOD
|
Yes | No | Truncated |
Common Lisp | mod
|
Yes | Yes | Floored |
rem
|
Yes | Yes | Truncated | |
Crystal | %
|
Yes | No | Truncated |
D | %
|
Yes | Yes | Truncated[13] |
Dart | %
|
Yes | Yes | Euclidean |
remainder()
|
Yes | Yes | Truncated | |
Eiffel | \\
|
Yes | No | Truncated |
Elixir | rem/2
|
Yes | No | Truncated[14] |
Integer.mod/2
|
Yes | No | Floored[15] | |
Elm | modBy
|
Yes | No | Floored |
remainderBy
|
Yes | No | Truncated | |
Erlang | rem
|
Yes | No | Truncated |
Euphoria | mod
|
Yes | No | Floored |
remainder
|
Yes | No | Truncated | |
F# | %
|
Yes | Yes | Truncated |
Factor | mod
|
Yes | No | Truncated |
FileMaker | Mod
|
Yes | No | Floored |
Forth | mod
|
Yes | No | Implementation defined |
fm/mod
|
Yes | No | Floored | |
sm/rem
|
Yes | No | Truncated | |
Fortran | mod
|
Yes | Yes | Truncated |
modulo
|
Yes | Yes | Floored | |
Frink | mod
|
Yes | No | Floored |
GameMaker Studio (GML) | mod , %
|
Yes | No | Truncated |
GDScript (Godot) | %
|
Yes | No | Truncated |
fmod
|
No | Yes | Truncated | |
posmod
|
Yes | No | Floored | |
fposmod
|
No | Yes | Floored | |
Go | %
|
Yes | No | Truncated |
math.Mod
|
No | Yes | Truncated | |
Groovy | %
|
Yes | No | Truncated |
Haskell | mod
|
Yes | No | Floored |
rem
|
Yes | No | Truncated | |
Data.Fixed.mod' (GHC)
|
No | Yes | Floored | |
Haxe | %
|
Yes | No | Truncated |
J | | [b]
|
Yes | No | Floored |
Java | %
|
Yes | Yes | Truncated |
Math.floorMod
|
Yes | No | Floored | |
JavaScript | %
|
Yes | Yes | Truncated |
Julia | mod
|
Yes | No | Floored |
% , rem
|
Yes | No | Truncated | |
Kotlin | % , rem
|
Yes | Yes | Truncated |
ksh | %
|
Yes | No | Truncated (same as POSIX sh) |
fmod
|
No | Yes | Truncated | |
LabVIEW | mod
|
Yes | Yes | Truncated |
LibreOffice | =MOD()
|
Yes | No | Floored |
Logo | MODULO
|
Yes | No | Floored |
REMAINDER
|
Yes | No | Truncated | |
Lua 5 | %
|
Yes | No | Floored |
Lua 4 | mod(x,y)
|
Yes | No | Floored |
Liberty BASIC | MOD
|
Yes | No | Truncated |
Mathcad | mod(x,y)
|
Yes | No | Floored |
Maple | e mod m
|
Yes | No | Euclidean |
Mathematica | Mod[a, b]
|
Yes | No | Floored |
MATLAB | mod
|
Yes | No | Floored |
rem
|
Yes | No | Truncated | |
Maxima | mod
|
Yes | No | Floored |
remainder
|
Yes | No | Truncated | |
Maya Embedded Language | %
|
Yes | No | Truncated |
Microsoft Excel | =MOD()
|
Yes | Yes | Floored |
Minitab | MOD
|
Yes | No | Floored |
Modula-2 | MOD
|
Yes | No | Floored |
REM
|
Yes | No | Truncated | |
MUMPS | #
|
Yes | No | Floored |
Netwide Assembler (NASM, NASMX) | % , div (unsigned)
|
Yes | No | — |
%% (signed)
|
Yes | No | Implementation-defined[16] | |
Nim | mod
|
Yes | No | Truncated |
Oberon | MOD
|
Yes | No | Floored-like[d] |
Objective-C | %
|
Yes | No | Truncated (same as C99) |
Object Pascal, Delphi | mod
|
Yes | No | Truncated |
OCaml | mod
|
Yes | No | Truncated |
mod_float
|
No | Yes | Truncated | |
Occam | \
|
Yes | No | Truncated |
Pascal (ISO-7185 and -10206) | mod
|
Yes | No | Euclidean-like[e] |
Programming Code Advanced (PCA) | \
|
Yes | No | Undefined |
Perl | %
|
Yes | No | Floored[f] |
POSIX::fmod
|
No | Yes | Truncated | |
Phix | mod
|
Yes | No | Floored |
remainder
|
Yes | No | Truncated | |
PHP | %
|
Yes | No | Truncated |
fmod
|
No | Yes | Truncated | |
PIC BASIC Pro | \\
|
Yes | No | Truncated |
PL/I | mod
|
Yes | No | Floored (ANSI PL/I) |
PowerShell | %
|
Yes | No | Truncated |
Programming Code (PRC) | MATH.OP - 'MOD; (\)'
|
Yes | No | Undefined |
Progress | modulo
|
Yes | No | Truncated |
Prolog (ISO 1995) | mod
|
Yes | No | Floored |
rem
|
Yes | No | Truncated | |
PureBasic | % , Mod(x,y)
|
Yes | No | Truncated |
PureScript | `mod`
|
Yes | No | Floored |
Python | %
|
Yes | Yes | Floored |
math.fmod
|
No | Yes | Truncated | |
Q# | %
|
Yes | No | Truncated[18] |
R | %%
|
Yes | No | Floored |
Racket | modulo
|
Yes | No | Floored |
remainder
|
Yes | No | Truncated | |
Raku | %
|
No | Yes | Floored |
RealBasic | MOD
|
Yes | No | Truncated |
Reason | mod
|
Yes | No | Truncated |
Rexx | //
|
Yes | Yes | Truncated |
RPG | %REM
|
Yes | No | Truncated |
Ruby | % , modulo()
|
Yes | Yes | Floored |
remainder()
|
Yes | Yes | Truncated | |
Rust | %
|
Yes | Yes | Truncated |
rem_euclid()
|
Yes | Yes | Euclidean[19] | |
SAS | MOD
|
Yes | No | Truncated |
Scala | %
|
Yes | No | Truncated |
Scheme | modulo
|
Yes | No | Floored |
remainder
|
Yes | No | Truncated | |
Scheme R6RS | mod
|
Yes | No | Euclidean[20] |
mod0
|
Yes | No | Rounded[20] | |
flmod
|
No | Yes | Euclidean | |
flmod0
|
No | Yes | Rounded | |
Scratch | mod
|
Yes | No | Floored |
mod
|
No | Yes | Truncated | |
Seed7 | mod
|
Yes | Yes | Floored |
rem
|
Yes | Yes | Truncated | |
SenseTalk | modulo
|
Yes | No | Floored |
rem
|
Yes | No | Truncated | |
sh (POSIX) (includes bash, mksh, &c.)
|
%
|
Yes | No | Truncated (same as C)[21] |
Smalltalk | \\
|
Yes | No | Floored |
rem:
|
Yes | No | Truncated | |
Snap! | mod
|
Yes | No | Floored |
Spin | //
|
Yes | No | Floored |
Solidity | %
|
Yes | No | Floored |
SQL (SQL:1999) | mod(x,y)
|
Yes | No | Truncated |
SQL (SQL:2011) | %
|
Yes | No | Truncated |
Standard ML | mod
|
Yes | No | Floored |
Int.rem
|
Yes | No | Truncated | |
Real.rem
|
No | Yes | Truncated | |
Stata | mod(x,y)
|
Yes | No | Euclidean |
Swift | %
|
Yes | No | Truncated |
truncatingRemainder(dividingBy:)
|
No | Yes | Truncated | |
Tcl | %
|
Yes | No | Floored |
TypeScript | %
|
Yes | No | Truncated |
Torque | %
|
Yes | No | Truncated |
Turing | mod
|
Yes | No | Floored |
Verilog (2001) | %
|
Yes | No | Truncated |
VHDL | mod
|
Yes | No | Floored |
rem
|
Yes | No | Truncated | |
VimL | %
|
Yes | No | Truncated |
Visual Basic | Mod
|
Yes | No | Truncated |
WebAssembly | i32.rem_s , i64.rem_s
|
Yes | No | Truncated |
x86 assembly | IDIV
|
Yes | No | Truncated |
XBase++ | %
|
Yes | Yes | Truncated |
Mod()
|
Yes | Yes | Floored | |
Z3 theorem prover | div , mod
|
Yes | No | Euclidean |
In addition, many computer systems provide a divmod
functionality, which produces the quotient and the remainder at the same time. Examples include the x86 architecture's IDIV
instruction, the C programming language's div()
function, and Python's divmod()
function.
Generalizations
Modulo with offset
Sometimes it is useful for the result of a modulo n to lie not between 0 and n−1, but between some number d and d+n−1. In that case, d is called an offset. There does not seem to be a standard notation for this operation, so let us tentatively use a modd n. We thus have the following definition:[22] x = a modd n just in case d ≤ x ≤ d+n−1 and x mod n = a mod n. Clearly, the usual modulo operation corresponds to zero offset: a mod n = a mod0 n. The operation of modulo with offset is related to the floor function as follows:
- .
(This is easy to see. Let . We first show that x mod n = a mod n. It is in general true that (a+bn) mod n = a mod n for all integers b; thus, this is true also in the particular case when b = ; but that means that , which is what we wanted to prove. It remains to be shown that d ≤ x ≤ d+n−1. Let k and r be the integers such that a − d = kn + r with 0 ≤ r ≤ n-1 (see Euclidean division). Then , thus . Now take 0 ≤ r ≤ n−1 and add d to both sides, obtaining d ≤ d + r ≤ d+n−1. But we've seen that x = d + r, so we are done. □)
The modulo with offset a modd n is implemented in Mathematica as[22] Mod[a, n, d]
.
Implementing other modulo definitions using truncation
Despite the mathematic elegance of Kunth'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:[6]
/* 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};
}
Note that 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) – many uses of the word modulo, all of which grew out of Carl F. Gauss's introduction of modular arithmetic in 1801.
- Modulo (mathematics), general use of the term in mathematics
- Modular exponentiation
- Turn (unit)
Notes
- ^ Mathematically, these two choices are but two of the infinite number of choices available for the inequality satisfied by a remainder.
- ^ a b Argument order reverses, i.e.,
α|ω
computes , the remainder when dividingω
byα
. - ^ As implemented in ACUCOBOL, Micro Focus COBOL, and possible others.
- ^ Divisor must be positive, otherwise undefined.
- ^ As discussed by Boute, ISO Pascal's definitions of
div
andmod
do not obey the Division Identity, and are thus fundamentally broken. - ^ Perl usually uses arithmetic modulo operator that is machine-independent. For examples and exceptions, see the Perl documentation on multiplicative operators.[17]
References
- ^ "The Definitive Glossary of Higher Mathematical Jargon: Modulo". Math Vault. 2019-08-01. Retrieved 2020-08-27.
- ^ Weisstein, Eric W. "Congruence". mathworld.wolfram.com. Retrieved 2020-08-27.
- ^ Caldwell, Chris. "residue". Prime Glossary. Retrieved August 27, 2020.
- ^ Knuth, Donald. E. (1972). The Art of Computer Programming. Addison-Wesley.
- ^ Boute, Raymond T. (April 1992). "The Euclidean definition of the functions div and mod". ACM Transactions on Programming Languages and Systems. 14 (2). ACM Press (New York, NY, USA): 127–144. doi:10.1145/128861.128862. hdl:1854/LU-314490.
- ^ a b Leijen, Daan (December 3, 2001). "Division and Modulus for Computer Scientists" (PDF). Retrieved 2014-12-25.
- ^ Peterson, Doctor (5 July 2001). "Mod Function and Negative Numbers". Math Forum - Ask Dr. Math. Retrieved 22 October 2019.
- ^ Horvath, Adam (July 5, 2012). "Faster division and modulo operation - the power of two".
- ^ "ISO/IEC 14882:2003: Programming languages – C++". International Organization for Standardization (ISO), International Electrotechnical Commission (IEC). 2003. sec. 5.6.4.
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
{{cite journal}}
: Cite journal requires|journal=
(help) - ^ "ISO/IEC 9899:1990: Programming languages – C". ISO, IEC. 1990. sec. 7.5.6.4.
The
fmod
function returns the valuex - i * y
, for some integeri
such that, ify
is nonzero, the result as the same sign asx
and magnitude less than the magnitude ofy
.{{cite journal}}
: Cite journal requires|journal=
(help) - ^ "C99 specification (ISO/IEC 9899:TC2)" (PDF). 2005-05-06. sec. 6.5.5 Multiplicative operators. Retrieved 16 August 2018.
- ^ CoffeeScript operators
- ^ "Expressions". D Programming Language 2.0. Digital Mars. Retrieved 29 July 2010.
- ^ "Kernel — Elixir v1.11.3". hexdocs.pm. Retrieved 2021-01-28.
- ^ "Integer — Elixir v1.11.3". hexdocs.pm. Retrieved 2021-01-28.
- ^ "Chapter 3: The NASM Language". NASM - The Netwide Assembler version 2.15.05.
- ^ Perl documentation
- ^ QuantumWriter. "Expressions". docs.microsoft.com. Retrieved 2018-07-11.
- ^ [1]
- ^ a b r6rs.org
- ^ "Shell Command Language". pubs.opengroup.org. Retrieved 2021-02-05.
- ^ a b "Mod". Wolfram Language & System Documentation Center. Wolfram Research. 2020. Retrieved April 8, 2020.
External links
- Modulorama, animation of a cyclic representation of multiplication tables (explanation in French)