Modulo¶
The mod
operator is used to give the remainder when one number
is divided by another.
For example, 11 mod 2
is 1
, because 2
fits into 11
five
times, with a remainder of 1; 11 mod 4
is 3
, because dividing
11
by 4
leaves a remainder of 3
.
Disco> 11 mod 2
1
Disco> 11 mod 4
3
Disco> 6 mod 2
0
Disco> 6 mod 7
6
Disco> (-7) mod 2
1
Formally, the result of mod
is defined in terms of the “Division
Algorithm”: given a number \(n\) and a positive divisor \(d\), the
remainder n mod d
is the unique number \(r\) such that \(n
= qd + r\), where \(0 \leq r < d\) and \(q\) is the
quotient. (For negative divisors, we
instead require \(d < r \leq 0\).)