Main Page: Difference between revisions

From formulasearchengine
Jump to navigation Jump to search
mNo edit summary
No edit summary
 
(361 intermediate revisions by more than 100 users not shown)
Line 1: Line 1:
[[Image:Divmod.svg|thumb|right|250px|Quotient (red) and remainder (green) functions using different algorithms]]
This is a preview for the new '''MathML rendering mode''' (with SVG fallback), which is availble in production for registered users.
In [[computing]], the '''modulo''' (sometimes called '''modulus''') operation finds the [[remainder]] of [[division (mathematics)|division]] of one number by another.


Given two positive numbers, {{math|''a''}} (the [[Division (mathematics)|dividend]]) and {{math|''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. (Note that doing the division with a calculator won't show the result referred to here by this operation; the quotient will be expressed as a decimal fraction.)
If you would like use the '''MathML''' rendering mode, you need a wikipedia user account that can be registered here [[https://en.wikipedia.org/wiki/Special:UserLogin/signup]]
* Only registered users will be able to execute this rendering mode.
* Note: you need not enter a email address (nor any other private information). Please do not use a password that you use elsewhere.


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]].
Registered users will be able to choose between the following three rendering modes:


When either {{math|''a''}} or {{math|''n''}} is negative, the naive definition breaks down and programming languages differ in how these values are defined.
'''MathML'''
:<math forcemathmode="mathml">E=mc^2</math>


__TOC__
<!--'''PNG'''  (currently default in production)
{{clear}}
:<math forcemathmode="png">E=mc^2</math>


==Remainder calculation for the modulo operation==
'''source'''
:<math forcemathmode="source">E=mc^2</math> -->


{| class="wikitable"  style="float:right; margin-left:1em; margin-right:0; width:30%;"
<span style="color: red">Follow this [https://en.wikipedia.org/wiki/Special:Preferences#mw-prefsection-rendering link] to change your Math rendering settings.</span> You can also add a [https://en.wikipedia.org/wiki/Special:Preferences#mw-prefsection-rendering-skin Custom CSS] to force the MathML/SVG rendering or select different font families. See [https://www.mediawiki.org/wiki/Extension:Math#CSS_for_the_MathML_with_SVG_fallback_mode these examples].
|+ Integer modulo operators in various programming languages
|-
! Language
! Operator
! abbr="Sign" | Result has the same sign as
|-
| [[ActionScript]] || <tt>%</tt> || Dividend
|-
| rowspan="2" | [[Ada (programming language)|Ada]]
| <tt>mod</tt> || Divisor
|-
| <tt>rem</tt> || Dividend
|-
| [[Active Server Page|ASP]] || <tt>Mod</tt> || Not defined
|-
| [[ALGOL-68]] || <tt>÷×, mod</tt> || Always positive
|-
| [[AMPL]] || <tt>mod</tt> || Dividend
|-
| [[APL (programming language)|APL]] || <tt><nowiki>|</nowiki></tt> || Divisor
|-
| [[AppleScript]] || <tt>mod</tt> || Dividend
|-
| [[AWK]] || <tt>%</tt> || Dividend
|-
| [[BASIC]] || <tt>Mod</tt> || Not defined
|-
| [[Bash (Unix shell)|bash]] || <tt>%</tt> || Dividend
|-
| [[bc programming language|bc]] || <tt>%</tt> || Dividend
|-
| [[C (programming language)|C]] (ISO 1990) || <tt>%</tt> || Implementation defined
|-
| [[C99|C (ISO 1999)]] || <tt>%</tt> || Dividend<ref name="C99">[http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf open-std.org], section 6.5.5</ref>
|-
| [[C++]] (ISO 1998) || <tt>%</tt> || Implementation defined<ref>{{Cite document|title=ISO/IEC 14882:2003 : Programming languages -- C++|publisher=[[International Organization for Standardization|ISO]], [[International Electrotechnical Commission|IEC]]|year=2003|location=5.6.4|postscript=<!--None-->}}. "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>
|-
| [[C++11|C++ (ISO 2011)]] || <tt>%</tt> || Dividend
|-
| [[C Sharp (programming language)|C#]] || <tt>%</tt> || Dividend
|-
| [[Clarion (programming language)|CLARION]] || <tt>%</tt> || Dividend
|-
| [[Clojure]] || <tt>mod</tt> || Divisor
|-
| [[COBOL]]{{ref|4}} || <tt>FUNCTION&nbsp;MOD</tt> || Divisor
|-
| [[ColdFusion]] || <tt>%, MOD</tt> || Dividend
|-
| rowspan="2" | [[Common Lisp]]
| <tt>mod</tt> || Divisor
|-
| <tt>rem</tt> || Dividend
|-
| [[D (programming language)|D]] || <tt>%</tt> || Dividend<ref>{{cite web|title=Expressions|url=http://www.digitalmars.com/d/2.0/expression.html#MulExpression|work=D Programming Language 2.0|publisher=Digital Mars|accessdate=29 July 2010}}</ref>
|-
| rowspan="2" | [[Dart (programming language)|Dart]] || <tt>%</tt> || Always Positive
|-
| remainder() || Dividend
|-
| [[Eiffel (programming language)|Eiffel]] || <tt>\\</tt> || Dividend
|-
| [[Erlang (programming language)|Erlang]] || <tt>rem</tt> || Dividend
|-
| rowspan="2" | [[Euphoria (programming language)|Euphoria]]
| <tt>mod</tt> || Divisor
|-
| <tt>remainder</tt> || Dividend
|-
| [[F Sharp (programming language)|F#]] || <tt>%</tt> || Dividend
|-
| [[FileMaker]] || <tt>Mod</tt> || Divisor
|-
| [[Forth (programming language)|Forth]] || <tt>mod</tt> || implementation defined
|-
| rowspan="2" | [[Fortran]]
| <tt>mod</tt> || Dividend
|-
| <tt>modulo</tt> || Divisor
|-
| [[Frink (programming language)|Frink]] || <tt>mod</tt> || Divisor
|-
| [[GameMaker: Studio|GML (Game Maker)]] || <tt>mod</tt> || Dividend
|-
| [[GDScript]] || <tt>mod</tt> || Dividend
|-
| [[Go (programming language)|Go]] || <tt>%</tt> || Dividend
|-
| rowspan="2" | [[Haskell (programming language)|Haskell]]
| <tt>mod</tt> || Divisor
|-
| <tt>rem</tt> || Dividend
|-
| [[J (programming language)|J]] || <tt><nowiki>|~</nowiki></tt> || Divisor
|-
| [[Java (programming language)|Java]] || <tt>%</tt> || Dividend
|-
| [[JavaScript]] || <tt>%</tt> || Dividend
|-
| [[Lua (programming language)|Lua 5]] || <tt>%</tt> || Divisor
|-
| [[Lua (programming language)|Lua 4]] || <tt>mod(x,y)</tt> || Divisor
|-
| [[Liberty Basic]] || <tt>MOD</tt> || Dividend
|-
| [[MathCad]] || <tt>mod(x,y) || Divisor
|-
| [[Maple (software)|Maple]] || <tt> e mod m </tt> || Always positive
|-
| [[Mathematica]] || <tt>Mod</tt> || Divisor
|-
| rowspan="2" | [[MATLAB]]
| <tt>mod</tt> || Divisor
|-
| <tt>rem</tt> || Dividend
|-
| rowspan="2" | [[Maxima (software)|Maxima]]
| <tt>mod</tt> || Divisor
|-
| <tt>remainder</tt> || Dividend
|-
| [[Maya Embedded Language]] || <tt>%<tt> || Always positive
|-
| [[Microsoft Excel]] || <tt>=MOD()<tt> || Divisor
|-
| [[Minitab]] || <tt>MOD<tt> || Divisor
|-
| [[Korn shell|mksh]] || <tt>%</tt> || Dividend
|-
| [[Modula-2]] || <tt>MOD<tt> || Divisor{{ref|3}}
|-
| [[MUMPS]] || <tt>#</tt> || Divisor
|-
| rowspan="2" | [[Netwide Assembler|NASM]] [[Netwide Assembler|NASMX]]
|  <tt>%</tt> || Unsigned Modulo Operator
|-
|  <tt>%%</tt> || Signed Modulo Operator
|-
| [[Oberon (programming language)|Oberon]] || <tt>MOD</tt> || Divisor{{ref|3}}
|-
| [[OCaml]] || <tt>mod</tt> || Dividend
|-
| [[Occam (programming language)|Occam]] || <tt>\</tt> || Dividend
|-
| [[Pascal (programming language)|Pascal (Delphi)]] || <tt>mod</tt> || Dividend
|-
| [[Pascal (programming language)|Pascal (ISO-7185 and ISO-10206)]] || <tt>mod</tt> || Always positive
|-
| [[Perl]] || <tt>%</tt> || Dividend<ref name="Perl v5.10.1">[http://www.compileonline.com/execute_perl_online.php execute perl online]</ref>
|-
| [[PHP]] || <tt>%</tt> || Dividend
|-
| [[PIC Basic Pro]] || <tt>\\</tt> || Dividend
|-
| [[PL/I]] || <tt>mod</tt> || Divisor (ANSI PL/I)
|-
| [[PowerBuilder]] || <tt>mod(x,y)</tt> || ?
|-
| [[PowerShell]] || <tt>%</tt> || Dividend
|-
| [[OpenEdge Advanced Business Language|Progress]] || <tt>modulo</tt> || Dividend
|-
| rowspan="2"| [[Prolog]] (ISO 1995)
| <tt>mod</tt> || Divisor
|-
| <tt>rem</tt> || Dividend
|-[[PureBasic]] || <tt>%,Mod(Number,Divisor)</tt>
|-
| [[Python (programming language)|Python]] || <tt>%</tt> || Divisor
|-
| [[Racket (programming language)|Racket]] || <tt>remainder</tt> || Dividend
|-
| [[RealBasic]] || <tt>MOD</tt> || Dividend
|-
| [[R (programming language)|R]] || <tt>%%</tt> || Divisor
|-
| [[REXX (programming language)|REXX]] || <tt>//</tt> || Dividend
|-
| [[RPG (programming language)|RPG]] || <tt>%REM</tt> || Dividend
|-
| rowspan="2" | [[Ruby (programming language)|Ruby]]
|  <tt>%, modulo()</tt> || Divisor
|-
|  <tt>remainder()</tt> || Dividend
|-
| [[Scala (programming language)|Scala]] || <tt>%</tt> || Dividend
|-
| rowspan="2" | [[Scheme (programming language)|Scheme]]
| <tt>modulo</tt> || Divisor
|-
| <tt>remainder</tt> || Dividend
|-
| rowspan="2" | [[Scheme (programming language)|Scheme]] R<sup>6</sup>RS
| <tt>mod</tt> || Always positive<ref name="r6rs">[http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_sec_11.7.3.1 r6rs.org]</ref>
|-
| <tt>mod0</tt> || Closest to zero<ref name="r6rs"/>
|-
| rowspan="2" | [[Seed7]]
| <tt>mod</tt> || Divisor
|-
| <tt>rem</tt> || Dividend
|-
| rowspan="2" | [[SenseTalk]]
| <tt>modulo</tt> || Divisor
|-
| <tt>rem</tt> || Dividend
|-
| rowspan="2" | [[Smalltalk]]
| <tt>\\</tt> || Divisor
|-
| <tt>rem:</tt> || Dividend
|-
| [[SQL]] ([[SQL:1999]]) || <tt>mod(x,y)</tt> || Dividend
|-
| rowspan="2" | [[Standard ML]]
| <tt>mod</tt> || Divisor
|-
| <tt>Int.rem</tt> || Dividend
|-
| [[Stata]] || <tt>mod(x,y)</tt> || Always positive
|-
| [[Tcl]] || <tt>%</tt> || Divisor
|-
| [[Torque Game Engine]] || <tt>%</tt> || Dividend
|-
| [[Turing (programming language)|Turing]] || <tt>mod</tt> || Divisor
|-
| [[Verilog]] (2001) || <tt>%</tt> || Dividend
|-
| rowspan="2" | [[VHDL]]
| <tt>mod</tt> || Divisor
|-
| <tt>rem</tt> || Dividend
|-
| [[Visual Basic]]||<tt>Mod</tt>||Dividend
|-
| [[x86 assembly language|x86 Assembly]] || <tt>IDIV</tt> || Dividend
|}
{| class="wikitable"  style="float:right; clear:right; margin-left:1em; margin-right:0; width:30%;"
|+ Floating-point modulo operators in various programming languages
|-
! Language
! Operator
! abbr="Sign" | Result has the same sign as
|-
| [[C (programming language)|C]] (ISO 1990) || <tt>fmod</tt> || ?
|-
| rowspan="2" | [[C99|C (ISO 1999)]]
| <tt>fmod</tt> || Dividend
|-
| <tt>remainder</tt> || Closest to zero
|-
| [[C++]] (ISO 1998) || <tt>std::fmod</tt> || ?
|-
| rowspan="2" | [[C++11|C++ (ISO 2011)]]
| <tt>std::fmod</tt> || Dividend
|-
| <tt>std::remainder</tt> || Closest to zero
|-
| [[C Sharp (programming language)|C#]] || <tt>%</tt> || Dividend
|-
| rowspan="2" | [[Common Lisp]]
| <tt>mod</tt> || Divisor
|-
| <tt>rem</tt> || Dividend
|-
| [[D (programming language)|D]] || <tt>%</tt> || Dividend
|-
| rowspan="2" | [[Dart (programming language)|Dart]] || <tt>%</tt> || Always Positive
|-
| remainder() || Dividend
|-
| [[F Sharp (programming language)|F#]] || <tt>%</tt> || Dividend
|-
| rowspan="2" | [[Fortran]]
| <tt>mod</tt> || Dividend
|-
| <tt>modulo</tt> || Divisor
|-
| [[Go (programming language)|Go]] || <tt>math.Fmod</tt> || Dividend
|-
| [[Haskell (programming language)|Haskell]] (GHC) || <tt>Data.Fixed.mod'</tt> || Divisor
|-
| [[Java (programming language)|Java]] || <tt>%</tt> || Dividend
|-
| [[JavaScript]] || <tt>%</tt> || Dividend
|-
| [[OCaml]] || <tt>mod_float</tt> || Dividend
|-
| [[Perl]] || <tt>POSIX::fmod</tt> || Dividend
|-
| [[Perl6]] || <tt>%</tt> || Divisor
|-
| [[PHP]] || <tt>fmod</tt> || Dividend
|-
| rowspan="2"| [[Python (programming language)|Python]]
| <tt>%</tt> || Divisor
|-
| <tt>math.fmod</tt> || Dividend
|-
| [[REXX (programming language)|REXX]] || <tt>//</tt> || Dividend
|-
| rowspan="2" | [[Ruby (programming language)|Ruby]]
| <tt>%, modulo()</tt> || Divisor
|-
| <tt>remainder()</tt> || Dividend
|-
| rowspan="2" | [[Scheme (programming language)|Scheme]] R<sup>6</sup>RS
| <tt>flmod</tt> || Always positive
|-
| <tt>flmod0</tt> || Closest to zero
|-
| [[Standard ML]] || <tt>Real.rem</tt> || 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 [[computer hardware|hardware]].


In nearly all computing systems, the [[quotient]] {{math|''q''}} and the remainder {{math|''r''}} satisfy
==Demos==
: <math>q \in \mathbb{Z}</math>
: <math>a = n \times q + r\,</math>
: <math>\left| r \right| < \left| n \right|.</math>


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''.{{ref|2}} 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''.
Here are some [https://commons.wikimedia.org/w/index.php?title=Special:ListFiles/Frederic.wang demos]:


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''=''a'' − ''n'' ''q''. Informally speaking the quotient is "rounded towards zero", and the remainder therefore has the same sign as the dividend.


[[Donald Knuth|Knuth]]<ref>{{cite book|
* accessibility:
first=Donald. E.|last=Knuth|title=The Art of Computer Programming
** Safari + VoiceOver: [https://commons.wikimedia.org/wiki/File:VoiceOver-Mac-Safari.ogv video only], [[File:Voiceover-mathml-example-1.wav|thumb|Voiceover-mathml-example-1]], [[File:Voiceover-mathml-example-2.wav|thumb|Voiceover-mathml-example-2]], [[File:Voiceover-mathml-example-3.wav|thumb|Voiceover-mathml-example-3]], [[File:Voiceover-mathml-example-4.wav|thumb|Voiceover-mathml-example-4]], [[File:Voiceover-mathml-example-5.wav|thumb|Voiceover-mathml-example-5]], [[File:Voiceover-mathml-example-6.wav|thumb|Voiceover-mathml-example-6]], [[File:Voiceover-mathml-example-7.wav|thumb|Voiceover-mathml-example-7]]
|publisher=Addison-Wesley|year=1972
** [https://commons.wikimedia.org/wiki/File:MathPlayer-Audio-Windows7-InternetExplorer.ogg Internet Explorer + MathPlayer (audio)]
}}</ref> described '''floored division''' where the quotient is defined by the [[floor function]] ''q''=floor(''a''/''n'') and the remainder ''r'' is
** [https://commons.wikimedia.org/wiki/File:MathPlayer-SynchronizedHighlighting-WIndows7-InternetExplorer.png Internet Explorer + MathPlayer (synchronized highlighting)]
:<math>r = a - nq = a - n \left\lfloor {a \over n} \right\rfloor.</math>
** [https://commons.wikimedia.org/wiki/File:MathPlayer-Braille-Windows7-InternetExplorer.png Internet Explorer + MathPlayer (braille)]
Here the quotient is always rounded downwards (even if it is already negative) and the remainder has the same sign as the divisor.
** NVDA+MathPlayer: [[File:Nvda-mathml-example-1.wav|thumb|Nvda-mathml-example-1]], [[File:Nvda-mathml-example-2.wav|thumb|Nvda-mathml-example-2]], [[File:Nvda-mathml-example-3.wav|thumb|Nvda-mathml-example-3]], [[File:Nvda-mathml-example-4.wav|thumb|Nvda-mathml-example-4]], [[File:Nvda-mathml-example-5.wav|thumb|Nvda-mathml-example-5]], [[File:Nvda-mathml-example-6.wav|thumb|Nvda-mathml-example-6]], [[File:Nvda-mathml-example-7.wav|thumb|Nvda-mathml-example-7]].
** Orca: There is ongoing work, but no support at all at the moment [[File:Orca-mathml-example-1.wav|thumb|Orca-mathml-example-1]], [[File:Orca-mathml-example-2.wav|thumb|Orca-mathml-example-2]], [[File:Orca-mathml-example-3.wav|thumb|Orca-mathml-example-3]], [[File:Orca-mathml-example-4.wav|thumb|Orca-mathml-example-4]], [[File:Orca-mathml-example-5.wav|thumb|Orca-mathml-example-5]], [[File:Orca-mathml-example-6.wav|thumb|Orca-mathml-example-6]], [[File:Orca-mathml-example-7.wav|thumb|Orca-mathml-example-7]].
** From our testing, ChromeVox and JAWS are not able to read the formulas generated by the MathML mode.


Raymond T. Boute<ref>{{cite journal
==Test pages ==
  | last = Boute
  | first = Raymond T.
  | title = The Euclidean definition of the functions div and mod
  | journal = ACM Transactions on Programming Languages and Systems (TOPLAS)
  | 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}}</ref> 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:
: <math>q \in \mathbb{Z}</math>
: <math>a = n \times q + r\,</math>
: <math>0 \leq r < |n|.</math>


Two corollaries are that
To test the '''MathML''', '''PNG''', and '''source''' rendering modes, please go to one of the following test pages:
: <math>n > 0 \Rightarrow q = \left\lfloor \frac{a}{n} \right\rfloor</math>
*[[Displaystyle]]
: <math>n < 0 \Rightarrow q = \left\lceil \frac{a}{n} \right\rceil,</math>
*[[MathAxisAlignment]]
or, equivalently,
*[[Styling]]
: <math>q = \sgn(n) \left\lfloor \frac{a}{\left|n\right|} \right\rfloor.</math>
*[[Linebreaking]]
*[[Unique Ids]]
*[[Help:Formula]]


As described by Leijen,<ref>{{cite web
*[[Inputtypes|Inputtypes (private Wikis only)]]
  | last = Leijen
*[[Url2Image|Url2Image (private Wikis only)]]
  | first = Daan
==Bug reporting==
  | title = Division and Modulus for Computer Scientists
If you find any bugs, please report them at [https://bugzilla.wikimedia.org/enter_bug.cgi?product=MediaWiki%20extensions&component=Math&version=master&short_desc=Math-preview%20rendering%20problem Bugzilla], or write an email to math_bugs (at) ckurs (dot) de .
  | date = December 3, 2001
  | url = http://www.cs.uu.nl/~daan/download/papers/divmodnote.pdf
  | format = PDF
  | accessdate =2006-08-27  }}</ref>
: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 {{math|<var>q</var>{{=}}round(<var>a</var>/<var>n</var>)}}, {{math|q{{=}}ceil(<var>a</var>/<var>n</var>)}}.
[[IEEE 754-1985|IEEE 754]] defines a remainder function where the quotient is {{math|<var>a</var>/<var>n</var>}} rounded according to the [[IEEE 754-1985#Rounding floating-point numbers|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:
 
<source lang="cpp">
bool is_odd(int n) {
    return n % 2 == 1;
}
</source>
 
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):
 
<source lang="cpp">
bool is_odd(int n) {
    return n % 2 != 0;
}
</source>
 
Or, by understanding in the first place that for any odd number, the modulo remainder may be either 1 or -1:
 
<source lang="cpp">
bool is_odd(int n) {
    return n % 2 == 1 || n % 2 == -1;
}
</source>
 
==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 (programming)|operator]], such as
:<code>a % n</code>
 
or
:<code>a mod n</code>
 
or equivalent, for environments lacking a mod() function (note that 'int' inherently produces the floor value of a/n)
 
:<code>a - (n * int(a/n))</code>.
 
==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 operation|bitwise AND]] operation:
:<code>x % 2<sup>n</sup> == x & (2<sup>n</sup> - 1)</code>.
 
Examples (assuming x is a positive integer):
:<code>x % 2 == x & 1</code>
:<code>x % 4 == x & 3</code>
:<code>x % 8 == x & 7</code>.
 
In devices and software that implement bitwise operations more efficiently than modulo, these alternative forms can result in faster calculations. <ref>{{cite web | first = Adam | last = Horvath | url =http://blog.teamleadnet.com/2012/07/faster-division-and-modulo-operation.html | title = Faster division and modulo operation - the power of two | date = July 5, 2012 }}</ref>
 
[[Compiler optimization|Optimizing]] [[compiler]]s may recognize expressions of the form <code>expression % constant</code> where <code>constant</code> is a power of two and automatically implement them as <code>expression & (constant-1)</code>. 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, <code>expression & (constant-1)</code> will always produce a positive result. So special treatment has to be made when the dividend can be negative.)
 
==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:
**<math>(a\,\bmod\,n)\,\bmod\,n = a\,\bmod\,n</math>
**<math>n^x\,\bmod\,n = 0</math> for all positive integer values of <math>x</math>.
** If <math>n</math> is a [[prime number]] which is not a [[divisor]] of <math>b</math>, then <math>ab^{n-1}\,\bmod\,n = a\,\bmod\,n</math>, due to [[Fermat's little theorem]].
*Inverse:
**<math>((-a\,\bmod\,n) + (a\,\bmod\,n))\,\bmod\,n =0</math>
**<math>b^{-1}\,\bmod\,n</math> denotes the [[modular multiplicative inverse]], which is defined if and only if <math>b</math> and <math>n</math> are [[relatively prime]], which is the case when the left hand side is defined: <math>((b^{-1}\,\bmod\,n) \, (b\,\bmod\,n))\,\bmod\,n =1</math>.
*Distributive:
**<math>(a+b)\,\bmod\,n = ((a\,\bmod\,n)+(b\,\bmod\,n))\,\bmod\,n</math>
**<math>ab\,\bmod\,n = ((a\,\bmod\,n)\,(b\,\bmod\,n))\,\bmod\,n</math>
*Division (definition):  <math>\frac{a}{b}\,\bmod\,n = ((a\,\bmod\,n)(b^{-1}\,\bmod\,n))\,\bmod\,n</math>, when the right hand side is defined. Not defined otherwise.
*Inverse Multiplication:  <math>((ab\,\bmod\,n)\,(b^{-1}\,\bmod\,n))\,\bmod\,n = a\,\bmod\,n</math>
 
===Common misconceptions===
It is a common mistake to believe that <math>\frac{a}{b}\,\bmod\,n = \frac{a\,\bmod\,n}{b\,\bmod\,n}</math> for rational numbers; however this property '''is not true''', for instance
<math>\frac{24}{3}\,\bmod\,5 = 8\,\bmod\,5 = 3</math> but <math>\frac{24\,\bmod\,5}{3\,\bmod\,5} = \frac{4}{3} \neq 3</math>.
 
Another common mistake is to forget the last <math>\bmod\,n</math> in the above formulas. Using the same example
<math>((24\,\bmod\,5)(3^{-1}\,\bmod\,5)) = 4 \cdot 2 = 8 \neq 3</math>; however <math>8\,\bmod\,5 = 3</math>.
 
==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.
*[[Modular exponentiation]]
 
==Notes==
* {{note|1}} Perl usually uses arithmetic modulo operator that is machine-independent. See the [http://perldoc.perl.org/perlop.html#Multiplicative-Operators Perl documentation] for exceptions and examples.
* {{note|2}} Mathematically, these two choices are but two of the infinite number of choices available for [[remainder#The inequality satisfied by the remainder|the inequality satisfied by a remainder]].
* {{note|3}} Divisor must be positive, otherwise not defined.
* {{note|4}} As implemented in ACUCOBOL, Micro Focus COBOL, and possibly others.
 
==References==
<references/>
 
==External links==
{{DEFAULTSORT:Modulo Operation}}
[[Category:Computer arithmetic]]
[[Category:Articles with example C++ code]]
[[Category:Operators (programming)]]
[[Category:Modular arithmetic]]
[[Category:Binary operations]]
[[de:Division mit Rest#Modulo]]

Latest revision as of 23:52, 15 September 2019

This is a preview for the new MathML rendering mode (with SVG fallback), which is availble in production for registered users.

If you would like use the MathML rendering mode, you need a wikipedia user account that can be registered here [[1]]

  • Only registered users will be able to execute this rendering mode.
  • Note: you need not enter a email address (nor any other private information). Please do not use a password that you use elsewhere.

Registered users will be able to choose between the following three rendering modes:

MathML


Follow this link to change your Math rendering settings. You can also add a Custom CSS to force the MathML/SVG rendering or select different font families. See these examples.

Demos

Here are some demos:


Test pages

To test the MathML, PNG, and source rendering modes, please go to one of the following test pages:

Bug reporting

If you find any bugs, please report them at Bugzilla, or write an email to math_bugs (at) ckurs (dot) de .