Modulo: Difference between revisions
DarthKitty (talk | contribs) →In programming languages: add CSS row; the spec <https://drafts.csswg.org/css-values/#funcdef-mod> isn't clear about the definition of `mod()`, but does say that "the result will either be zero or share the sign of [the divisor]", which matches the floored definition; according to the spec, "`rem()` is the behavior of JavaScript’s `%` operator" |
|||
(47 intermediate revisions by 25 users not shown) | |||
Line 1: | Line 1: | ||
{{About|the binary operation ''mod({{mvar|a,n}})''|the ''(mod {{mvar|n}})'' notation|Modular arithmetic|other uses}} |
{{About|the binary operation ''mod({{mvar|a,n}})''|the ''(mod {{mvar|n}})'' notation|Modular arithmetic|other uses}} |
||
{{short description|Computational operation}} |
{{short description|Computational operation}} |
||
In [[computing]], the '''modulo operation''' returns the [[remainder]] or signed remainder of a [[Division (mathematics)|division]], after one number is divided by another |
In [[computing]], the '''modulo operation''' returns the [[remainder]] or signed remainder of a [[Division (mathematics)|division]], after one number is divided by another, called the ''[[modular arithmetic|modulus]]'' of the operation. |
||
Given two positive numbers {{math|''a''}} and {{math|''n''}}, {{math|''a''}} modulo {{math|''n''}} (often abbreviated as {{math|''a'' mod ''n''}}) is the remainder of the [[Euclidean division]] of {{math|''a''}} by {{math|''n''}}, where {{math|''a''}} is the [[Division (mathematics)|dividend]] and {{math|''n''}} is the [[divisor]].<ref>{{Cite web|last=Weisstein|first=Eric W.|title=Congruence|url=https://mathworld.wolfram.com/Congruence.html|access-date=2020-08-27|website= |
Given two positive numbers {{math|''a''}} and {{math|''n''}}, {{math|''a''}} modulo {{math|''n''}} (often abbreviated as {{math|''a'' mod ''n''}}) is the remainder of the [[Euclidean division]] of {{math|''a''}} by {{math|''n''}}, where {{math|''a''}} is the [[Division (mathematics)|dividend]] and {{math|''n''}} is the [[divisor]].<ref>{{Cite web|last=Weisstein|first=Eric W.|title=Congruence|url=https://mathworld.wolfram.com/Congruence.html|access-date=2020-08-27|website=Wolfram MathWorld |language=en}}</ref> |
||
For example, the expression "5 mod 2" evaluates 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 9 divided by 3 has a quotient of 3 and a remainder of 0. |
For example, the expression "5 mod 2" evaluates 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 9 divided by 3 has a quotient of 3 and a remainder of 0. |
||
Line 15: | Line 15: | ||
In nearly all computing systems, the quotient {{math|''q''}} and the remainder {{math|''r''}} of {{math|''a''}} divided by {{math|''n''}} satisfy the following conditions: |
In nearly all computing systems, the quotient {{math|''q''}} and the remainder {{math|''r''}} of {{math|''a''}} divided by {{math|''n''}} satisfy the following conditions: |
||
{{NumBlk|::|<math>\begin{align} |
|||
&q \in \mathbb{Z} \\ |
&q \in \mathbb{Z} \\ |
||
&a = n q + r \\ |
&a = n q + r \\ |
||
Line 21: | Line 21: | ||
\end{align}</math>|{{EquationRef|1}}}} |
\end{align}</math>|{{EquationRef|1}}}} |
||
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 |
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 {{math|''a''}} or {{math|''n''}}.{{efn|Mathematically, these two choices are but two of the infinite number of choices available for [[remainder|the inequality satisfied by a remainder]].}} Standard [[Pascal (programming language)|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 {{math|''n''}} or {{math|''a''}} is negative (see the table under {{Section link||In programming languages}} for details). {{math|''a''}} modulo 0 is undefined in most systems, although some do define it as {{math|''a''}}. |
||
{{bulleted list |
{{bulleted list |
||
Line 27: | Line 27: | ||
Many implementations use ''truncated division'', for which the quotient is defined by |
Many implementations use ''truncated division'', for which the quotient is defined by |
||
: <math>q = \operatorname{trunc}\left(\frac{a}{n}\right)</math> |
: <math>q = \operatorname{trunc}\left(\frac{a}{n}\right)</math> |
||
where |
where <math>\operatorname{trunc}</math> is the [[Integral part|integral part function]] ([[Rounding#Rounding toward zero|rounding toward zero]]), i.e. the [[truncation]] to zero significant digits. |
||
Thus according to equation ({{EquationNote|1}}), the remainder has the ''same sign as the dividend'' {{var|a}} so can take {{math|1=2{{!}}''n''{{!}} − 1}} values: |
Thus according to equation ({{EquationNote|1}}), the remainder has the ''same sign as the dividend'' {{var|a}} so can take {{math|1=2{{!}}''n''{{!}} − 1}} values: |
||
: <math>r = a - n \operatorname{trunc}\left(\frac{a}{n}\right)</math> |
: <math>r = a - n \operatorname{trunc}\left(\frac{a}{n}\right)</math> |
||
Line 34: | Line 34: | ||
[[Donald Knuth]]<ref>{{cite book|first=Donald. E. |last=Knuth |title=The Art of Computer Programming |url=https://archive.org/details/artofcomputerpro0003knut |url-access=registration |publisher=Addison-Wesley |year=1972}}</ref> promotes ''floored division'', for which the quotient is defined by |
[[Donald Knuth]]<ref>{{cite book|first=Donald. E. |last=Knuth |title=The Art of Computer Programming |url=https://archive.org/details/artofcomputerpro0003knut |url-access=registration |publisher=Addison-Wesley |year=1972}}</ref> promotes ''floored division'', for which the quotient is defined by |
||
: <math>q = \left\lfloor\frac{a}{n}\right\rfloor</math> |
: <math>q = \left\lfloor\frac{a}{n}\right\rfloor</math> |
||
where |
where <math>\lfloor\,\rfloor</math> is the [[floor function]] ([[Rounding#Rounding down|rounding down]]). |
||
Thus according to equation ({{EquationNote|1}}), the remainder has the ''same sign as the divisor'' {{var|n}}: |
Thus according to equation ({{EquationNote|1}}), the remainder has the ''same sign as the divisor'' {{var|n}}: |
||
: <math>r = a - n \left\lfloor\frac{a}{n}\right\rfloor</math> |
: <math>r = a - n \left\lfloor\frac{a}{n}\right\rfloor</math> |
||
| |
|[[File:Divmod Euclidean.svg|thumb|upright=1.2|Quotient and remainder using Euclidean division]] |
||
Raymond T. Boute<ref>{{cite journal |last = Boute |first = Raymond T. |title = The Euclidean definition of the functions div and mod |journal = ACM Transactions on Programming Languages and Systems |volume = 14 |issue = 2 |pages = 127–144 |publisher = ACM Press (New York, NY, USA) |date = April 1992 |url = http://portal.acm.org/citation.cfm?id=128862&coll=portal&dl=ACM |doi = 10.1145/128861.128862| hdl = 1854/LU-314490 |s2cid = 8321674 |hdl-access = free}}</ref> promotes ''[[Euclidean division]]'', for which the quotient is defined by |
Raymond T. Boute<ref>{{cite journal |last = Boute |first = Raymond T. |title = The Euclidean definition of the functions div and mod |journal = ACM Transactions on Programming Languages and Systems |volume = 14 |issue = 2 |pages = 127–144 |publisher = ACM Press (New York, NY, USA) |date = April 1992 |url = http://portal.acm.org/citation.cfm?id=128862&coll=portal&dl=ACM |doi = 10.1145/128861.128862| hdl = 1854/LU-314490 |s2cid = 8321674 |hdl-access = free}}</ref> promotes ''[[Euclidean division]]'', for which the quotient is defined by |
||
: <math>q = \sgn(n) \left\lfloor\frac{a}{\left|n\right|}\right\rfloor = |
: <math>q = \sgn(n) \left\lfloor\frac{a}{\left|n\right|}\right\rfloor = |
||
Line 45: | Line 45: | ||
\left\lceil\frac{a}{n}\right\rceil & \text{if } n < 0 \\ |
\left\lceil\frac{a}{n}\right\rceil & \text{if } n < 0 \\ |
||
\end{cases}</math> |
\end{cases}</math> |
||
where {{math|sgn}} is the [[sign function]], |
where {{math|sgn}} is the [[sign function]], <math>\lfloor\,\rfloor</math> is the [[floor function]] ([[Rounding#Rounding down|rounding down]]), and <math>\lceil\,\rceil</math> is the [[ceiling function]] ([[Rounding#Rounding up|rounding up]]). |
||
Thus according to equation ({{EquationNote|1}}), the remainder is ''non negative'': |
Thus according to equation ({{EquationNote|1}}), the remainder is ''non negative'': |
||
: <math>r = a - |n| \left\lfloor\frac{a}{\left|n\right|}\right\rfloor</math> |
: <math>r = a - |n| \left\lfloor\frac{a}{\left|n\right|}\right\rfloor</math> |
||
Line 74: | Line 74: | ||
| first = Daan |
| first = Daan |
||
| title = Division and Modulus for Computer Scientists |
| title = Division and Modulus for Computer Scientists |
||
| website = [[Microsoft]] |
|||
| date = December 3, 2001 |
| date = December 3, 2001 |
||
| url = https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/divmodnote-letter.pdf |
| url = https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/divmodnote-letter.pdf |
||
Line 105: | Line 106: | ||
bool is_odd(int n) { |
bool is_odd(int n) { |
||
return n % 2 != 0; |
return n % 2 != 0; |
||
} |
|||
</syntaxhighlight> |
|||
Another alternative is to use the fact that for any odd number, the remainder may be either 1 or −1: |
|||
<syntaxhighlight lang="cpp"> |
|||
bool is_odd(int n) { |
|||
return n % 2 == 1 || n % 2 == -1; |
|||
} |
|||
</syntaxhighlight> |
|||
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: |
|||
<syntaxhighlight lang="cpp"> |
|||
bool is_odd(int n) { |
|||
return n % 2; |
|||
} |
} |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
Line 141: | Line 126: | ||
==Properties (identities)== |
==Properties (identities)== |
||
{{see also|Modular arithmetic#Properties}} |
{{see also|Modular arithmetic#Properties}} |
||
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]]. |
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]]. The properties involving multiplication, division, and exponentiation generally require that {{math|''a''}} and {{math|''n''}} are integers. |
||
* Identity: |
* Identity: |
||
** {{math|(''a'' mod ''n'') mod ''n'' {{=}} ''a'' mod ''n''}}. |
** {{math|(''a'' mod ''n'') mod ''n'' {{=}} ''a'' mod ''n''}}. |
||
Line 184: | Line 169: | ||
| {{yes}} |
| {{yes}} |
||
| {{no}} |
| {{no}} |
||
| Floored<ref name="Ada">{{Cite |
| Floored<ref name="Ada">{{Cite book|title=ISO/IEC 8652:2012 - Information technology — Programming languages — Ada|publisher=[[International Organization for Standardization|ISO]], [[International Electrotechnical Commission|IEC]]|year=2012|at=sec. 4.5.5 Multiplying Operators}}</ref> |
||
|- |
|- |
||
| {{code|rem}} |
| {{code|rem}} |
||
Line 209: | Line 194: | ||
| <code><nowiki>|</nowiki></code>{{efn|name=rev|Argument order reverses, i.e., <code><nowiki>α|ω</nowiki></code> computes <math>\omega\bmod\alpha</math>, the remainder when dividing {{code|ω}} by {{code|α}}.}} |
| <code><nowiki>|</nowiki></code>{{efn|name=rev|Argument order reverses, i.e., <code><nowiki>α|ω</nowiki></code> computes <math>\omega\bmod\alpha</math>, the remainder when dividing {{code|ω}} by {{code|α}}.}} |
||
| {{yes}} |
| {{yes}} |
||
| {{ |
| {{yes}} |
||
| Floored |
| Floored |
||
Line 245: | Line 230: | ||
| {{yes}} |
| {{yes}} |
||
| {{no}} |
| {{no}} |
||
| Varies by implementation |
|||
| Undefined |
|||
|- |
|- |
||
Line 259: | Line 244: | ||
| {{yes}} |
| {{yes}} |
||
| {{no}} |
| {{no}} |
||
| Truncated{{efn|name=c|[[C99]] and [[C++11]] define the behavior of {{code|%}} to be truncated.<ref name="C99">{{cite web |title=C99 specification (ISO/IEC 9899:TC2) |url=http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf |access-date=16 August 2018 |at=sec. 6.5.5 Multiplicative operators |date=2005-05-06}}</ref> The standards before then leave the behavior implementation-defined.<ref>{{Cite |
| Truncated{{efn|name=c|[[C99]] and [[C++11]] define the behavior of {{code|%}} to be truncated.<ref name="C99">{{cite web |title=C99 specification (ISO/IEC 9899:TC2) |url=http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf |access-date=16 August 2018 |at=sec. 6.5.5 Multiplicative operators |date=2005-05-06}}</ref> The standards before then leave the behavior implementation-defined.<ref>{{Cite book|year=2003|title=ISO/IEC 14882:2003: Programming languages – C++|publisher=[[International Organization for Standardization]] (ISO), [[International Electrotechnical Commission]] (IEC)|at=sec. 5.6.4|quote=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}}</ref>}} |
||
|- |
|- |
||
| {{code|fmod}} (C){{break}}{{code|std::fmod}} (C++) |
| {{code|fmod}} (C){{break}}{{code|std::fmod}} (C++) |
||
| {{no}} |
| {{no}} |
||
| {{yes}} |
| {{yes}} |
||
| Truncated<ref>{{Cite |
| Truncated<ref>{{Cite book|title=ISO/IEC 9899:1990: Programming languages – C |publisher=[[International Organization for Standardization|ISO]], [[International Electrotechnical Commission|IEC]] |year=1990 |at=sec. 7.5.6.4 |quote=The {{math|fmod}} function returns the value {{math|x - i * y}}, for some integer {{math|i}} such that, if {{math|y}} is nonzero, the result has the same sign as {{math|x}} and magnitude less than the magnitude of {{math|y}}.}}</ref> |
||
|- |
|- |
||
| {{code|remainder}} (C){{break}}{{code|std::remainder}} (C++) |
| {{code|remainder}} (C){{break}}{{code|std::remainder}} (C++) |
||
Line 281: | Line 266: | ||
| {{no}} |
| {{no}} |
||
| {{yes}} |
| {{yes}} |
||
| Rounded<ref name=".NET">{{Cite web |last=dotnet-bot |title=Math.IEEERemainder(Double, Double) Method (System) |url=https://learn.microsoft.com/en-us/dotnet/api/system.math.ieeeremainder?view=net-7.0 |access-date=2022-10-04 |website= |
| Rounded<ref name=".NET">{{Cite web |last=dotnet-bot |title=Math.IEEERemainder(Double, Double) Method (System) |url=https://learn.microsoft.com/en-us/dotnet/api/system.math.ieeeremainder?view=net-7.0 |access-date=2022-10-04 |website=Microsoft Learn |language=en-us}}</ref> |
||
|- |
|- |
||
Line 314: | Line 299: | ||
| {{yes}} |
| {{yes}} |
||
| {{no}} |
| {{no}} |
||
| Floored<ref name="isocobol">{{cite book|title=ISO/IEC 1989:2023 – Programming language COBOL|author=ISO/IEC JTC 1/SC 22/WG 4|publisher=[[ISO]]|date=January 2023|url=https://www.iso.org/standard/74527.html|url-access=subscription}}</ref> |
|||
| Floored<ref name="isocobol">{{cite book |
|||
| title=ISO/IEC 1989:2023 – Programming language COBOL |
|||
| author=ISO/IEC JTC 1/SC 22/WG 4 |
|||
| publisher=[[ISO]] |
|||
| date=January 2023 |
|||
| url=https://www.iso.org/standard/74527.html |
|||
| url-access=subscription |
|||
}}</ref> |
|||
|- |
|- |
||
| {{code|FUNCTION REM}} |
| {{code|FUNCTION REM}} |
||
Line 382: | Line 360: | ||
| {{yes}} |
| {{yes}} |
||
| Truncated |
| Truncated |
||
⚫ | |||
| rowspan="2"| [[CSS]] |
|||
⚫ | |||
⚫ | |||
⚫ | |||
| Floored<ref>{{Cite web |date=2024-06-22 |title=mod() - CSS: Cascading Style Sheets {{!}} MDN |url=https://developer.mozilla.org/en-US/docs/Web/CSS/mod |access-date=2024-10-23 |website=developer.mozilla.org |language=en-US}}</ref> |
|||
|- |
|||
| {{code|rem()}} |
|||
| {{yes}} |
|||
| {{yes}} |
|||
| Truncated<ref>{{Cite web |date=2024-10-15 |title=rem() - CSS: Cascading Style Sheets {{!}} MDN |url=https://developer.mozilla.org/en-US/docs/Web/CSS/rem |access-date=2024-10-23 |website=developer.mozilla.org |language=en-US}}</ref> |
|||
|- |
|- |
||
Line 518: | Line 508: | ||
| {{no}} |
| {{no}} |
||
| Floored |
| Floored |
||
|- |
|||
| rowspan="2" | [[Full BASIC]] |
|||
| {{code|MOD}} |
|||
| {{yes}} |
|||
| {{yes}} |
|||
| Floored<ref>{{cite book|last=[[ANSI]]|title=Programming Languages — Full BASIC|url=https://archive.org/details/federalinformat6821nati_0|date=28 January 1987|publisher=American National Standards Institute|location=New York|at=§ 5.4.4|quote=X modulo Y, i.e., X-Y*INT(X/Y).}}</ref> |
|||
|- |
|||
| {{code|REMAINDER}} |
|||
| {{yes}} |
|||
| {{yes}} |
|||
| Truncated<ref>{{cite book|last=[[ANSI]]|title=Programming Languages — Full BASIC|url=https://archive.org/details/federalinformat6821nati_0|date=28 January 1987|publisher=American National Standards Institute|location=New York|at=§ 5.4.4|quote="The remainder function, i.e., X-Y*IP(X/Y)."}}</ref> |
|||
|- |
|- |
||
Line 553: | Line 555: | ||
| {{yes}} |
| {{yes}} |
||
| {{no}} |
| {{no}} |
||
| Euclidean |
|||
| Floored |
|||
|- |
|- |
||
| {{code|fposmod}} |
| {{code|fposmod}} |
||
| {{no}} |
| {{no}} |
||
| {{yes}} |
| {{yes}} |
||
| Euclidean |
|||
| Floored |
|||
|- |
|- |
||
| rowspan=" |
| rowspan="4" | [[Go (programming language)|Go]] |
||
| {{code|%}} |
| {{code|%}} |
||
| {{yes}} |
| {{yes}} |
||
Line 576: | Line 578: | ||
| {{no}} |
| {{no}} |
||
| Euclidean<ref>{{Cite web |title=big package - math/big - pkg.go.dev |url=https://pkg.go.dev/math/big#Int.Mod |access-date=2022-02-28 |website=pkg.go.dev}}</ref> |
| Euclidean<ref>{{Cite web |title=big package - math/big - pkg.go.dev |url=https://pkg.go.dev/math/big#Int.Mod |access-date=2022-02-28 |website=pkg.go.dev}}</ref> |
||
|- |
|||
| {{code|big.Int.Rem}} |
|||
| {{yes}} |
|||
| {{no}} |
|||
| Truncated<ref>{{Cite web |title=big package - math/big - pkg.go.dev |url=https://pkg.go.dev/math/big#Int.Rem |access-date=2024-04-12 |website=pkg.go.dev}}</ref> |
|||
|- |
|- |
||
| [[Apache Groovy|Groovy]] |
| [[Apache Groovy|Groovy]] |
||
Line 613: | Line 619: | ||
| {{yes}} |
| {{yes}} |
||
| {{yes}} |
| {{yes}} |
||
| Undefined<ref>{{cite web |url=https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-operators#additive-and-multiplicative-operators |title=Operators |author=<!--Not stated--> |publisher=[[Microsoft]] |access-date=2021-07-19 |quote=The % operator is defined only in cases where either both sides are positive or both sides are negative. Unlike C, it also operates on floating-point data types, as well as integers.}}</ref> |
| Undefined<ref>{{cite web |url=https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-operators#additive-and-multiplicative-operators |title=Operators |author=<!--Not stated--> |date=30 June 2021 |publisher=[[Microsoft]] |access-date=2021-07-19 |quote=The % operator is defined only in cases where either both sides are positive or both sides are negative. Unlike C, it also operates on floating-point data types, as well as integers.}}</ref> |
||
|- |
|- |
||
Line 884: | Line 890: | ||
| {{no}} |
| {{no}} |
||
| Euclidean-like{{efn|1=As discussed by Boute, ISO Pascal's definitions of {{code|div}} and {{code|mod}} do not obey the Division Identity of {{math|1=''D'' = ''d'' · (''D'' / ''d'') + ''D'' % ''d''}}, and are thus fundamentally broken.}} |
| Euclidean-like{{efn|1=As discussed by Boute, ISO Pascal's definitions of {{code|div}} and {{code|mod}} do not obey the Division Identity of {{math|1=''D'' = ''d'' · (''D'' / ''d'') + ''D'' % ''d''}}, and are thus fundamentally broken.}} |
||
⚫ | |||
| Programming Code Advanced ([[Principal component analysis|PCA]]) |
|||
⚫ | |||
⚫ | |||
⚫ | |||
| Undefined |
|||
|- |
|- |
||
Line 1,002: | Line 1,001: | ||
|- |
|- |
||
| rowspan=" |
| rowspan="3" | [[Python (programming language)|Python]] |
||
| {{code|%}} |
| {{code|%}} |
||
| {{yes}} |
| {{yes}} |
||
Line 1,012: | Line 1,011: | ||
| {{yes}} |
| {{yes}} |
||
| Truncated |
| Truncated |
||
|- |
|||
| {{code|math.remainder}} |
|||
| {{no}} |
|||
| {{yes}} |
|||
| Rounded |
|||
|- |
|- |
||
Line 1,109: | Line 1,113: | ||
| {{code|%}} |
| {{code|%}} |
||
| {{yes}} |
| {{yes}} |
||
| {{ |
| {{yes}} |
||
| Truncated |
| Truncated |
||
Line 1,215: | Line 1,219: | ||
| {{yes}} |
| {{yes}} |
||
| {{no}} |
| {{no}} |
||
| Truncated<ref>{{Cite web|title=Solidity Documentation|url=https://docs.soliditylang.org/en/v0.8.28/types.html|access-date=2024-10-17|website=docs.soliditylang.org}}</ref> |
|||
| Floored |
|||
|- |
|- |
||
Line 1,343: | Line 1,347: | ||
| {{yes}} |
| {{yes}} |
||
| {{no}} |
| {{no}} |
||
| {{N/A}}<ref>{{ |
| {{N/A}}<ref name="wasmcs2">{{cite web|editor-first1=Andreas|editor-last1=Rossberg|date=19 April 2022|title=WebAssembly Core Specification: Version 2.0|url=https://www.w3.org/TR/wasm-core-2/|publisher=[[World Wide Web Consortium]]|at=§ 4.3.2 Integer Operations}}</ref> |
||
|- |
|- |
||
| {{code|i32.rem_s}}, {{code|i64.rem_s}} (signed) |
| {{code|i32.rem_s}}, {{code|i64.rem_s}} (signed) |
||
| {{yes}} |
| {{yes}} |
||
| {{no}} |
| {{no}} |
||
| Truncated<ref name="wasmcs2" /> |
|||
| Truncated<ref>{{Cite web |title=Numerics — WebAssembly 1.1 (Draft 2022-03-02) |url=https://webassembly.github.io/spec/core/exec/numerics.html#op-irem-s |access-date=2022-03-16 |website=webassembly.github.io}}</ref> |
|||
|- |
|- |
||
Line 1,397: | Line 1,401: | ||
The operation of modulo with offset is related to the [[Floor and ceiling functions|floor function]] as follows: |
The operation of modulo with offset is related to the [[Floor and ceiling functions|floor function]] as follows: |
||
::<math>a \operatorname{mod}_d n = a - n \left\lfloor\frac{a-d}{n}\right\rfloor.</math> |
::<math>a \operatorname{mod}_d n = a - n \left\lfloor\frac{a-d}{n}\right\rfloor.</math> |
||
To see this, let <math display="inline">x = a - n \left\lfloor\frac{a-d}{n}\right\rfloor</math>. We first show that {{math|1=''x'' mod ''n'' = ''a'' mod ''n''}}. It is in general true that {{math|1=(''a'' + ''bn'') mod ''n'' = ''a'' mod ''n''}} for all integers {{mvar|b}}; thus, this is true also in the particular case when <math display="inline">b = -\!\left\lfloor\frac{a-d}{n}\right\rfloor</math>; but that means that <math display="inline">x \bmod n = \left(a - n \left\lfloor\frac{a-d}{n}\right\rfloor\right)\! \bmod n = a \bmod n</math>, which is what we wanted to prove. It remains to be shown that {{math|''d'' ≤ ''x'' ≤ ''d'' + ''n'' − 1}}. Let {{mvar|k}} and {{mvar|r}} be the integers such that {{math|1=''a'' − ''d'' = ''kn'' + ''r''}} with {{math|0 ≤ ''r'' ≤ ''n'' − 1}} (see [[Euclidean division]]). Then <math display="inline">\left\lfloor\frac{a-d}{n}\right\rfloor = k</math>, thus <math display="inline">x = a - n \left\lfloor\frac{a-d}{n}\right\rfloor = a - n k = d +r</math>. Now take {{math|0 ≤ ''r'' ≤ ''n'' − 1}} and add {{mvar|d}} to both sides, obtaining {{math|''d'' ≤ ''d'' + ''r'' ≤ ''d'' + ''n'' − 1}}. But we've seen that {{math|1=''x'' = ''d'' + ''r''}}, so we are done. |
To see this, let <math display="inline">x = a - n \left\lfloor\frac{a-d}{n}\right\rfloor</math>. We first show that {{math|1=''x'' mod ''n'' = ''a'' mod ''n''}}. It is in general true that {{math|1=(''a'' + ''bn'') mod ''n'' = ''a'' mod ''n''}} for all integers {{mvar|b}}; thus, this is true also in the particular case when <math display="inline">b = -\!\left\lfloor\frac{a-d}{n}\right\rfloor</math>; but that means that <math display="inline">x \bmod n = \left(a - n \left\lfloor\frac{a-d}{n}\right\rfloor\right)\! \bmod n = a \bmod n</math>, which is what we wanted to prove. It remains to be shown that {{math|''d'' ≤ ''x'' ≤ ''d'' + ''n'' − 1}}. Let {{mvar|k}} and {{mvar|r}} be the integers such that {{math|1=''a'' − ''d'' = ''kn'' + ''r''}} with {{math|0 ≤ ''r'' ≤ ''n'' − 1}} (see [[Euclidean division]]). Then <math display="inline">\left\lfloor\frac{a-d}{n}\right\rfloor = k</math>, thus <math display="inline">x = a - n \left\lfloor\frac{a-d}{n}\right\rfloor = a - n k = d +r</math>. Now take {{math|0 ≤ ''r'' ≤ ''n'' − 1}} and add {{mvar|d}} to both sides, obtaining {{math|''d'' ≤ ''d'' + ''r'' ≤ ''d'' + ''n'' − 1}}. But we've seen that {{math|1=''x'' = ''d'' + ''r''}}, so we are done. |
||
The modulo with offset {{math|''a'' mod<sub>''d''</sub> ''n''}} is implemented in [[Mathematica]] as {{code|Mod[a, n, d]}} .<ref name="Mathematica Mod" /> |
The modulo with offset {{math|''a'' mod<sub>''d''</sub> ''n''}} is implemented in [[Mathematica]] as {{code|Mod[a, n, d]}} .<ref name="Mathematica Mod" /> |
Latest revision as of 06:09, 23 October 2024
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 (often 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]
For example, the expression "5 mod 2" evaluates 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 9 divided by 3 has a quotient of 3 and a remainder of 0.
Although typically performed with a and n both being integers, many computing systems now allow other types of numeric operands. The range of values for an integer modulo operation of n is 0 to n − 1 (a mod 1 is always 0; a mod 0 is undefined, being a division by zero).
When exactly one of a or n is negative, the basic definition breaks down, and programming languages differ in how these values are defined.
Variants of the definition
[edit]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).[2] 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) |
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 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, for which the quotient is defined by
where is the integral part function (rounding toward zero), i.e. the truncation to zero significant digits. Thus according to equation (1), the remainder has the same sign as the dividend a so can take 2|n| − 1 values:
-
Donald Knuth[3] promotes floored division, for which the quotient is defined by
where is the floor function (rounding down). Thus according to equation (1), the remainder has the same sign as the divisor n:
-
Raymond T. Boute[4] promotes Euclidean division, for which the quotient is defined by
where sgn is the sign function, is the floor function (rounding down), and is the ceiling function (rounding up). Thus according to equation (1), the remainder is non negative:
-
Common Lisp and IEEE 754 use rounded division, for which the quotient is defined by
where round is the round function (rounding half to even). Thus according to equation (1), the remainder falls between and , and its sign depends on which side of zero it falls to be within these boundaries:
-
Common Lisp also uses ceiling division, for which the quotient is defined by
where ⌈⌉ is the ceiling function (rounding up). Thus according to equation (1), the remainder has the opposite sign of that of the divisor:
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.
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[5]
However, truncated division satisfies the identity .[6]
Notation
[edit]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
[edit]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 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;
}
Performance issues
[edit]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.[7]
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.
Optimizations for general constant-modulus operations also exist by calculating the division first using the constant-divisor optimization.
Properties (identities)
[edit]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. The properties involving multiplication, division, and exponentiation generally require that a and n are integers.
- 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), and undefined otherwise.
- Inverse multiplication: [(ab mod n)(b−1 mod n)] mod n = a mod n.
In programming languages
[edit]Language | Operator | Integer | Floating-point | Definition |
---|---|---|---|---|
ABAP | MOD
|
Yes | Yes | Euclidean |
ActionScript | %
|
Yes | No | Truncated |
Ada | mod
|
Yes | No | Floored[8] |
rem
|
Yes | No | Truncated[8] | |
ALGOL 68 | ÷× , mod
|
Yes | No | Euclidean |
AMPL | mod
|
Yes | No | Truncated |
APL | | [b]
|
Yes | Yes | Floored |
AppleScript | mod
|
Yes | No | Truncated |
AutoLISP | (rem d n)
|
Yes | No | Truncated |
AWK | %
|
Yes | No | Truncated |
bash | %
|
Yes | No | Truncated |
BASIC | Mod
|
Yes | No | Varies by implementation |
bc | %
|
Yes | No | Truncated |
C C++ |
% , div
|
Yes | No | Truncated[c] |
fmod (C)std::fmod (C++)
|
No | Yes | Truncated[11] | |
remainder (C)std::remainder (C++)
|
No | Yes | Rounded | |
C# | %
|
Yes | Yes | Truncated |
Math.IEEERemainder
|
No | Yes | Rounded[12] | |
Clarion | %
|
Yes | No | Truncated |
Clean | rem
|
Yes | No | Truncated |
Clojure | mod
|
Yes | No | Floored[13] |
rem
|
Yes | No | Truncated[14] | |
COBOL | FUNCTION MOD
|
Yes | No | Floored[15] |
FUNCTION REM
|
Yes | Yes | Truncated[15] | |
CoffeeScript | %
|
Yes | No | Truncated |
%%
|
Yes | No | Floored[16] | |
ColdFusion | % , MOD
|
Yes | No | Truncated |
Common Intermediate Language | rem (signed)
|
Yes | Yes | Truncated[17] |
rem.un (unsigned)
|
Yes | No | — | |
Common Lisp | mod
|
Yes | Yes | Floored |
rem
|
Yes | Yes | Truncated | |
Crystal | % , modulo
|
Yes | Yes | Floored |
remainder
|
Yes | Yes | Truncated | |
CSS | mod()
|
Yes | Yes | Floored[18] |
rem()
|
Yes | Yes | Truncated[19] | |
D | %
|
Yes | Yes | Truncated[20] |
Dart | %
|
Yes | Yes | Euclidean[21] |
remainder()
|
Yes | Yes | Truncated[22] | |
Eiffel | \\
|
Yes | No | Truncated |
Elixir | rem/2
|
Yes | No | Truncated[23] |
Integer.mod/2
|
Yes | No | Floored[24] | |
Elm | modBy
|
Yes | No | Floored[25] |
remainderBy
|
Yes | No | Truncated[26] | |
Erlang | rem
|
Yes | No | Truncated |
math:fmod/2
|
No | Yes | Truncated (same as C)[27] | |
Euphoria | mod
|
Yes | No | Floored |
remainder
|
Yes | No | Truncated | |
F# | %
|
Yes | Yes | Truncated |
Math.IEEERemainder
|
No | Yes | Rounded[12] | |
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 |
Full BASIC | MOD
|
Yes | Yes | Floored[28] |
REMAINDER
|
Yes | Yes | Truncated[29] | |
GLSL | %
|
Yes | No | Undefined[30] |
mod
|
No | Yes | Floored[31] | |
GameMaker Studio (GML) | mod , %
|
Yes | No | Truncated |
GDScript (Godot) | %
|
Yes | No | Truncated |
fmod
|
No | Yes | Truncated | |
posmod
|
Yes | No | Euclidean | |
fposmod
|
No | Yes | Euclidean | |
Go | %
|
Yes | No | Truncated[32] |
math.Mod
|
No | Yes | Truncated[33] | |
big.Int.Mod
|
Yes | No | Euclidean[34] | |
big.Int.Rem
|
Yes | No | Truncated[35] | |
Groovy | %
|
Yes | No | Truncated |
Haskell | mod
|
Yes | No | Floored[36] |
rem
|
Yes | No | Truncated[36] | |
Data.Fixed.mod' (GHC)
|
No | Yes | Floored | |
Haxe | %
|
Yes | No | Truncated |
HLSL | %
|
Yes | Yes | Undefined[37] |
J | | [b]
|
Yes | No | Floored |
Java | %
|
Yes | Yes | Truncated |
Math.floorMod
|
Yes | No | Floored | |
JavaScript TypeScript |
%
|
Yes | Yes | Truncated |
Julia | mod
|
Yes | Yes | Floored[38] |
% , rem
|
Yes | Yes | Truncated[39] | |
Kotlin | % , rem
|
Yes | Yes | Truncated[40] |
mod
|
Yes | Yes | Floored[41] | |
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 | Yes | Floored |
Lua 4 | mod(x,y)
|
Yes | Yes | Truncated |
Liberty BASIC | MOD
|
Yes | No | Truncated |
Mathcad | mod(x,y)
|
Yes | No | Floored |
Maple | e mod m (by default), modp(e, m)
|
Yes | No | Euclidean |
mods(e, m)
|
Yes | No | Rounded | |
frem(e, m)
|
Yes | Yes | Rounded | |
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[42] | |
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[43] |
mod_float
|
No | Yes | Truncated[44] | |
Occam | \
|
Yes | No | Truncated |
Pascal (ISO-7185 and -10206) | mod
|
Yes | No | Euclidean-like[e] |
Perl | %
|
Yes | No | Floored[f] |
POSIX::fmod
|
No | Yes | Truncated | |
Phix | mod
|
Yes | No | Floored |
remainder
|
Yes | No | Truncated | |
PHP | %
|
Yes | No | Truncated[46] |
fmod
|
No | Yes | Truncated[47] | |
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 | Euclidean[48] |
Pure Data | %
|
Yes | No | Truncated (same as C) |
mod
|
Yes | No | Floored | |
Python | %
|
Yes | Yes | Floored |
math.fmod
|
No | Yes | Truncated | |
math.remainder
|
No | Yes | Rounded | |
Q# | %
|
Yes | No | Truncated[49] |
R | %%
|
Yes | Yes | Floored[50] |
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[51] | |
SAS | MOD
|
Yes | No | Truncated |
Scala | %
|
Yes | Yes | Truncated |
Scheme | modulo
|
Yes | No | Floored |
remainder
|
Yes | No | Truncated | |
Scheme R6RS | mod
|
Yes | No | Euclidean[52] |
mod0
|
Yes | No | Rounded[52] | |
flmod
|
No | Yes | Euclidean | |
flmod0
|
No | Yes | Rounded | |
Scratch | mod
|
Yes | Yes | Floored |
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)[53] |
Smalltalk | \\
|
Yes | No | Floored |
rem:
|
Yes | No | Truncated | |
Snap! | mod
|
Yes | No | Floored |
Spin | //
|
Yes | No | Floored |
Solidity | %
|
Yes | No | Truncated[54] |
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[55] |
remainder(dividingBy:)
|
No | Yes | Rounded[56] | |
truncatingRemainder(dividingBy:)
|
No | Yes | Truncated[57] | |
Tcl | %
|
Yes | No | Floored |
fmod()
|
No | Yes | Truncated (as C) | |
tcsh | %
|
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_u , i64.rem_u (unsigned)
|
Yes | No | —[58] |
i32.rem_s , i64.rem_s (signed)
|
Yes | No | Truncated[58] | |
x86 assembly | IDIV
|
Yes | No | Truncated |
XBase++ | %
|
Yes | Yes | Truncated |
Mod()
|
Yes | Yes | Floored | |
Zig | % ,
|
Yes | Yes | Truncated[59] |
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
[edit]Modulo with offset
[edit]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 and d = 1 is particularly common.
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:[60] 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:
To see this, 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 ; 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 Mod[a, n, d]
.[60]
Implementing other modulo definitions using truncation
[edit]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:[5]
/* 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
[edit]- Modulo (disambiguation) – 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 (angle)
Notes
[edit]- ^ 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α
. - ^ C99 and C++11 define the behavior of
%
to be truncated.[9] The standards before then leave the behavior implementation-defined.[10] - ^ Divisor must be positive, otherwise undefined.
- ^ As discussed by Boute, ISO Pascal's definitions of
div
andmod
do not obey the Division Identity of D = d · (D / d) + D % d, 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.[45]
References
[edit]- ^ Weisstein, Eric W. "Congruence". Wolfram MathWorld. 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. S2CID 8321674.
- ^ a b Leijen, Daan (December 3, 2001). "Division and Modulus for Computer Scientists" (PDF). Microsoft. Retrieved 2014-12-25.
- ^ Peterson, Doctor (5 July 2001). "Mod Function and Negative Numbers". Math Forum - Ask Dr. Math. Archived from the original on 2019-10-22. Retrieved 22 October 2019.
- ^ Horvath, Adam (July 5, 2012). "Faster division and modulo operation - the power of two".
- ^ a b ISO/IEC 8652:2012 - Information technology — Programming languages — Ada. ISO, IEC. 2012. sec. 4.5.5 Multiplying Operators.
- ^ "C99 specification (ISO/IEC 9899:TC2)" (PDF). 2005-05-06. sec. 6.5.5 Multiplicative operators. Retrieved 16 August 2018.
- ^ 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
- ^ ISO/IEC 9899:1990: Programming languages – C. ISO, IEC. 1990. sec. 7.5.6.4.
The fmod function returns the value x - i * y, for some integer i such that, if y is nonzero, the result has the same sign as x and magnitude less than the magnitude of y.
- ^ a b dotnet-bot. "Math.IEEERemainder(Double, Double) Method (System)". Microsoft Learn. Retrieved 2022-10-04.
- ^ "clojure.core - Clojure v1.10.3 API documentation". clojure.github.io. Retrieved 2022-03-16.
- ^ "clojure.core - Clojure v1.10.3 API documentation". clojure.github.io. Retrieved 2022-03-16.
- ^ a b ISO/IEC JTC 1/SC 22/WG 4 (January 2023). ISO/IEC 1989:2023 – Programming language COBOL. ISO.
{{cite book}}
: CS1 maint: numeric names: authors list (link) - ^ CoffeeScript operators
- ^ ISO/IEC JTC 1/SC 22 (February 2012). ISO/IEC 23271:2012 — Information technology — Common Language Infrastructure (CLI). ISO. §§ III.3.55–56.
{{cite book}}
: CS1 maint: numeric names: authors list (link) - ^ "mod() - CSS: Cascading Style Sheets | MDN". developer.mozilla.org. 2024-06-22. Retrieved 2024-10-23.
- ^ "rem() - CSS: Cascading Style Sheets | MDN". developer.mozilla.org. 2024-10-15. Retrieved 2024-10-23.
- ^ "Expressions - D Programming Language". dlang.org. Retrieved 2021-06-01.
- ^ "operator % method - num class - dart:core library - Dart API". api.dart.dev. Retrieved 2021-06-01.
- ^ "remainder method - num class - dart:core library - Dart API". api.dart.dev. Retrieved 2021-06-01.
- ^ "Kernel — Elixir v1.11.3". hexdocs.pm. Retrieved 2021-01-28.
- ^ "Integer — Elixir v1.11.3". hexdocs.pm. Retrieved 2021-01-28.
- ^ "Basics - core 1.0.5". package.elm-lang.org. Retrieved 2022-03-16.
- ^ "Basics - core 1.0.5". package.elm-lang.org. Retrieved 2022-03-16.
- ^ "Erlang -- math". erlang.org. Retrieved 2021-06-01.
- ^ ANSI (28 January 1987). Programming Languages — Full BASIC. New York: American National Standards Institute. § 5.4.4.
X modulo Y, i.e., X-Y*INT(X/Y).
- ^ ANSI (28 January 1987). Programming Languages — Full BASIC. New York: American National Standards Institute. § 5.4.4.
The remainder function, i.e., X-Y*IP(X/Y).
- ^ "GLSL Language Specification, Version 4.50.7" (PDF). section 5.9 Expressions.
If both operands are non-negative, then the remainder is non-negative. Results are undefined if one or both operands are negative.
- ^ "GLSL Language Specification, Version 4.50.7" (PDF). section 8.3 Common Functions.
- ^ "The Go Programming Language Specification - The Go Programming Language". go.dev. Retrieved 2022-02-28.
- ^ "math package - math - pkg.go.dev". pkg.go.dev. Retrieved 2022-02-28.
- ^ "big package - math/big - pkg.go.dev". pkg.go.dev. Retrieved 2022-02-28.
- ^ "big package - math/big - pkg.go.dev". pkg.go.dev. Retrieved 2024-04-12.
- ^ a b "6 Predefined Types and Classes". www.haskell.org. Retrieved 2022-05-22.
- ^ "Operators". Microsoft. 30 June 2021. Retrieved 2021-07-19.
The % operator is defined only in cases where either both sides are positive or both sides are negative. Unlike C, it also operates on floating-point data types, as well as integers.
- ^ "Mathematics · The Julia Language". docs.julialang.org. Retrieved 2021-11-20.
- ^ "Mathematics · The Julia Language". docs.julialang.org. Retrieved 2021-11-20.
- ^ "rem - Kotlin Programming Language". Kotlin. Retrieved 2021-05-05.
- ^ "mod - Kotlin Programming Language". Kotlin. Retrieved 2021-05-05.
- ^ "Chapter 3: The NASM Language". NASM - The Netwide Assembler version 2.15.05.
- ^ "OCaml library : Stdlib". ocaml.org. Retrieved 2022-02-19.
- ^ "OCaml library : Stdlib". ocaml.org. Retrieved 2022-02-19.
- ^ Perl documentation
- ^ "PHP: Arithmetic Operators - Manual". www.php.net. Retrieved 2021-11-20.
- ^ "PHP: fmod - Manual". www.php.net. Retrieved 2021-11-20.
- ^ "EuclideanRing".
- ^ QuantumWriter. "Expressions". docs.microsoft.com. Retrieved 2018-07-11.
- ^ "R: Arithmetic Operators". search.r-project.org. Retrieved 2022-12-24.
- ^ "F32 - Rust".
- ^ a b r6rs.org
- ^ "Shell Command Language". pubs.opengroup.org. Retrieved 2021-02-05.
- ^ "Solidity Documentation". docs.soliditylang.org. Retrieved 2024-10-17.
- ^ "Apple Developer Documentation". developer.apple.com. Retrieved 2021-11-20.
- ^ "Apple Developer Documentation". developer.apple.com. Retrieved 2021-11-20.
- ^ "Apple Developer Documentation". developer.apple.com. Retrieved 2021-11-20.
- ^ a b Rossberg, Andreas, ed. (19 April 2022). "WebAssembly Core Specification: Version 2.0". World Wide Web Consortium. § 4.3.2 Integer Operations.
- ^ "Zig Documentation". Zig Programming Language. Retrieved 2022-12-18.
- ^ a b "Mod". Wolfram Language & System Documentation Center. Wolfram Research. 2020. Retrieved April 8, 2020.
External links
[edit]- Different kinds of integer division
- Modulorama, animation of a cyclic representation of multiplication tables (explanation in French)