Mod
Details
- Mod is also known as modulo operation.
- Mathematical function, suitable for both symbolic and numerical manipulation.
- Typically used in modular arithmetic, cryptography, random number generation and cyclic operations in programs.
- Mod[m,n] gives the remainder of m divided by n.
- Mod[m,n] is equivalent to m-n Quotient[m,n].
- For positive integers m and n, Mod[m,n] is an integer between 0 and n-1.
- Mod[m,n,d] gives a result
such that
and
.
Examples
open all close allBasic Examples (4)
Mod[5, 3]The remainder on division of 5 by 3 offset to start with 1:
Mod[5, 3, 1]Plot the sequence with fixed modulus:
DiscretePlot[Mod[n, 8], {n, 50}]Plot the sequence, varying the modulus:
DiscretePlot[Mod[100, m], {m, 50}]Scope (13)
Numerical Evaluation (6)
Mod[17, 5]Mod[17, 5, 1]Mod works on integers:
Mod[17, 5]Mod[5 / 2, 2]Mod[Sqrt[28], 3]Mod[5 + 3I, 2]Mod[Pi, 2]Mod[3.14, 2.]Mod[10 ^ 10000, 10007]Mod threads over lists:
Mod[{1, 2, 3, 4, 5}, 3]TraditionalForm formatting:
Mod[a, n]//TraditionalFormSymbolic Manipulation (7)
Reduce[Mod[2x + 1, 5] == Mod[x, 7] && 0 < x < 50, x]Use Mod in a sum:
Sum[Mod[n ^ 2, 2], n]Product[Sin[(1/1 + Mod[i ^ 2, 3])], i]FullSimplify[Mod[a, -b] + Mod[-a, b] == 0]Identify Mod sequences:
FindSequenceFunction[{1, 2, 3, 4, 0, 1, 2, 3, 4, 0}, n]DifferenceRootReduce[Mod[k, 3], k]DirichletTransform[Mod[n, 2], n, s]GeneratingFunction[Mod[n, 4], n, x]ExponentialGeneratingFunction[Mod[n, 4], n, x]//FullSimplifyApplications (19)
Basic Applications (3)
The first 20 values of Mod:
Grid[{Prepend[Range[20], "n"], Prepend[Table[CarmichaelLambda[n], {n, 20}], "TraditionalFormλ(n)"]}, Background -> {None, {StandardOrange, StandardGray}}, Dividers -> Lighter[Gray, .5], Spacings -> {Automatic, .8}]Plot the sequence with a fixed modulus:
DiscretePlot[Mod[n, 8], {n, 50}]Plot the sequence, varying the modulus:
DiscretePlot[Mod[100, m], {m, 50}]Generating function of Mod[n,8]:
ModGF[z_] = GeneratingFunction[Mod[n, 8], n, z]GraphicsRow[{Plot[ModGF[x], {x, 0, 1}], ContourPlot[Re[ModGF[x + I * y]], {x, -1, 1}, {y, -1, 1}, ContourStyle -> None]}]Exponential generation function:
ModEGF[z_] = ExponentialGeneratingFunction[Mod[n, 8], n, z];GraphicsRow[{Plot[ModEGF[x], {x, 0, 16}], ContourPlot[Re[ModEGF[x + I * y]], {x, -1, 1}, {y, -1, 1}, ContourStyle -> None]}]ModL[s_] = Sum[Mod[n, 8] / n ^ s, {n, 1, Infinity}]GraphicsRow[{Plot[ModL[x], {x, 0, 16}], ContourPlot[Re[ModL[x + I * y]], {x, -1, 1}, {y, -1, 1}, ContourStyle -> None]}]Numeric Identifiers (1)
Given an International Standard Book Number (ISBN), check whether or not it is valid:
ISBNs = {"0394380495", "1092312213", "0821801236", "9781944183"};An ISBN is valid if
, where each
is the
digit of the ISBN:
ValidISBNQ[str_] := Module[
{l}, l = ToExpression[StringPartition[str, 1]];
If[Mod[Sum[l[[i]]i, {i, 10}], 11] == 0, True, False]
];Check if each of the ISBNs are valid:
ValidISBNQ /@ ISBNsCryptography (2)
Build an RSA-like encryption scheme. Start with the modulus:
{p, q} = Prime[RandomInteger[{10 ^ 4, 10 ^ 5}, {2}]];
n = p qFind the universal exponent of the multiplication group modulo n:
λ = CarmichaelLambda[n]d = NestWhile[#1 + 1& , Round[n / 3], GCD[λ, #1] =!= 1&]e = ModularInverse[d, λ]PowerMod[ToCharacterCode["RSA in Mathematica"], e, n]FromCharacterCode[PowerMod[%, d, n]]Use Mod to create a Caesar cipher that shifts letters in the alphabet to encrypt a message:
EncryptCaesar[msg_, key_] := Module[
{encr, decr, x, n, nums, res},
encr = Transpose[{Alphabet[], Range[0, 25]}] /. {x_String, n_Integer} -> (x -> n);
decr = Reverse[encr, 2];
nums = StringPartition[ToLowerCase[msg], 1] /. encr;
res = (Mod[nums + key, 26]) /. decr//StringJoin
];
DecryptCaesar[msg_, key_] := EncryptCaesar[msg, -key];key = 315;
msg = "bewaretheidesofmarch";
EncryptCaesar[msg, key]DecryptCaesar[%, key]Number Theory (6)
Check if numbers of the form
are prime or composite:
MersennePrimeQ[n_] := TrueQ[Last[NestList[Mod[# ^ 2 - 2, 2 ^ n - 1]&, 4, n - 2]] == 0];Select[Range[3, 100], MersennePrimeQ]Select primes below 100 having the form of
:
Select[Array[Prime, PrimePi[100]], Mod[#, 6] == 1&]GCD[7, 11]Mod[7 ^ (11 - 1), 11]GCD[7, 12]Mod[7 ^ EulerPhi[12], 12]FunctionExpand[Mod[(p - 1)!, p], p∈Primes]Define a notation for addition modulo 2:
x_⊕y_ := Mod[x + y, 2](1⊕0)⊕1Use Mod to solve systems of linear congruences:
r = {3, 5, 7};
m = {2, 3, 5};
M = (Times@@m/m);
Mod[Dot[r, #^EulerPhi[#]& /@ M], Times@@m]ChineseRemainder[r, m]Computer Sciences (3)
Create a random number generator that uses the current time as a seed:
x[0] = UnixTime[]
x[k_] := Mod[a^kx[0], m];m = 2147483647;
a = 16807;Compute 1000 random numbers between 0 and 1:
Histogram[Table[x[i] / m, {i, 0, 1000}], 10]Extract parts of a list cyclically:
{a, b, c}[[Mod[Range[10], 3, 1]]]Modular computation of a matrix inverse:
A = {{3, 4}, {2, 5}};First compute the matrix adjoint:
MinorMatrix[Mat_List ? MatrixQ] := Map[Reverse, Minors[Mat], {0, 1}]
CofactorMatrix[Mat_List ? MatrixQ] := MapIndexed[#1 (-1) ^ (Plus@@#2)&, MinorMatrix[Mat], {2}]
MatrixAdjoint[Mat_] := Transpose[CofactorMatrix[Mat]];Then compute the modular inverse of a matrix:
ModularInverseMatrix[Mat_, m_] := Mod[ModularInverse[Det[Mat], m]MatrixAdjoint[Mat], m];
ModularInverseMatrix[A, 13]Check that the inverse gives the correct result:
Mod[A.%, 13]Politics, Economics and Social Sciences (2)
Assign memory addresses to social security numbers based on a hashing algorithm:
socials = {344401659, 325510778, 212228844, 329938157, 047900151, 372500191, 034367980, 546332190, 509496993, 132489973};Assign each social a location, ensuring that there are no collisions:
AssignSingle[social_, locations_] := Module[
{i = 0},
While[MemberQ[locations[[ ;; , 2]], h[i, social]], i++];
Append[locations, {social, h[i, social]}]
];
AssignAll[socials_] := Module[
{l = Length[socials], locations = {}},
For[i = 1, i ≤ l, i++, locations = AssignSingle[socials[[i]], locations]];
locations
];AssignAll[socials]Compute the hash of a single social security number:
m = 4969;
num = 10 ^ 3 + 1;
g[k_] := Mod[k + 1, m - 2];
hash[k_] := Mod[k + num g[k], m];
social = 344401659;hash[social]Other Applications (2)
Simulate a particle bouncing in a noncommensurate box:
Graphics[Line[Table[Mod[t, {Sqrt[2], 1}], {t, 0, 15, .001}]]]System of 12-tone equal temperament:
Needs["Music`"]Sound[SoundNote[{"CSharp", "DFlat"}, 1, "Piano"]]Notes that have a difference of 1200 cents are considered to be from the same congruence class:
Mod[HertzToCents[{Csharp1, Csharp2}], 1200]Properties & Relations (7)
Mod is a periodic function:
FunctionPeriod[Mod[n, 3], n]Mod is defined over all complex numbers:
FunctionDomain[Mod[n, 3], n]FunctionRange[Mod[n, 3], n, m]Mod is transitive. If
and
, then
:
Mod[5, 3] == Mod[2, 3]Mod[2, 3] == Mod[8, 3]Mod[8, 3] == Mod[5, 3]Divisible[8, 2]Mod[8, 2]The QuotientRemainder[a,n] is the same as Mod[a,n]:
QuotientRemainder[17, 6]//LastMod[17, 6]Use PowerMod to compute the modular inverse:
PowerMod[3, -1, 7]Mod[3 5, 7]The results have the same sign as the modulus:
Mod[{5, -5}, 3]Mod[{5, -5}, -3]For a positive real number x, Mod[x,1] gives the fractional part of x:
Mod[3.14, 1]FractionalPart[3.14]Possible Issues (1)
Some computations may require higher internal precision than the default:
Mod[GoldenRatio ^ 1000, 1]Reset the value of $MaxExtraPrecision:
Block[{$MaxExtraPrecision = Infinity}, Mod[GoldenRatio ^ 1000, 1]]Neat Examples (4)
Binomial coefficients modulo 2:
ArrayPlot[Table[Mod[Binomial[i, j], 2], {i, 0, 63}, {j, 0, 63}]]ArrayPlot[CellularAutomaton[{Mod[Total[#], 4]&, {}, 1}, {{1}, 0}, 50]]Plot of an Ulam spiral where numbers are colored based on their congruence modulo 49:
ulam[n_] := Partition[Permute[Range[n ^ 2], Accumulate[Take[Flatten[{{n ^ 2 + 1} / 2, Table
[(-1) ^ j i, {j, n}, {i, {-1, n}}, {j}]}], n ^ 2]]], n]ArrayPlot[Mod[ulam[109], 109], ColorFunction -> "TemperatureMap"]ArrayPlot[Table[Mod[a + b, 4], {a, 0, 8}, {b, 0, 8}], ColorFunction -> "Rainbow"]History
Introduced in 1988 (1.0) | Updated in 1996 (3.0) ▪ 1999 (4.0) ▪ 2000 (4.1) ▪ 2002 (4.2)
Text
Wolfram Research (1988), Mod, Wolfram Language function, https://reference.wolfram.com/language/ref/Mod.html (updated 2002).
CMS
Wolfram Language. 1988. "Mod." Wolfram Language & System Documentation Center. Wolfram Research. Last Modified 2002. https://reference.wolfram.com/language/ref/Mod.html.
APA
Wolfram Language. (1988). Mod. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/Mod.html
BibTeX
@misc{reference.wolfram_2026_mod, author="Wolfram Research", title="{Mod}", year="2002", howpublished="\url{https://reference.wolfram.com/language/ref/Mod.html}", note=[Accessed: 13-June-2026]}
BibLaTeX
@online{reference.wolfram_2026_mod, organization={Wolfram Research}, title={Mod}, year={2002}, url={https://reference.wolfram.com/language/ref/Mod.html}, note=[Accessed: 13-June-2026]}