Conceptcore
Integer division and modulo
Also called integer division, modulo, modulo operation, mod, remainder, rem, truncated division, floored division, Euclidean division, floor division, divmod.
Integer division gives a whole quotient and a remainder. Languages round the quotient toward zero, toward minus infinity or by the Euclidean rule, so the sign of the remainder differs.
- Applies to
- core-languages
Idea
Integer division of a by n gives two integers: a quotient q and a remainder r. They satisfy a = n × q + r, and the size of r is less than the size of n. When a and n are both positive, there is one answer: 7 divided by 3 is 2 with remainder 1. When one of them is negative, there are two answers. -7 divided by 3 can be -2 with remainder -1, or -3 with remainder 2. Each language picks one rule.
Wikipedia lists the main rules1:
- Truncated division rounds the quotient toward zero. "the remainder has the same sign as the dividend"1. C, C++, Java, JavaScript, C#, Go and Rust use it for
/and%. - Floored division rounds the quotient down, toward minus infinity. Donald Knuth "promotes floored division"1, and with it "the remainder has the same sign as the divisor"1. Python uses it for
//and%. - Euclidean division picks the quotient that makes the remainder 0 or more. Raymond T. Boute "promotes Euclidean division"1. Rust has it in
div_euclidandrem_euclid.
def truncated(a, n):
q = abs(a) // abs(n)
if (a < 0) != (n < 0):
q = -q
return q, a - n * q
def floored(a, n):
return a // n, a % n
def euclidean(a, n):
r = a % abs(n)
return (a - r) // n, r
for a, n in ((7, 3), (-7, 3), (7, -3), (-7, -3)):
qt, rt = truncated(a, n)
qf, rf = floored(a, n)
qe, re = euclidean(a, n)
print(f"{a} / {n}: truncated {qt} r {rt}, floored {qf} r {rf}, "
f"Euclidean {qe} r {re}")
7 / 3: truncated 2 r 1, floored 2 r 1, Euclidean 2 r 1
-7 / 3: truncated -2 r -1, floored -3 r 2, Euclidean -3 r 2
7 / -3: truncated -2 r 1, floored -3 r -2, Euclidean -2 r 1
-7 / -3: truncated 2 r -1, floored 2 r -1, Euclidean 3 r 2
The three rules agree when the dividend is 0 or more and the divisor is positive. They differ only when a sign is negative.
How it works
The identity. Each language keeps the quotient and the remainder consistent. In C, "if the quotient a/b is representable in the result type, then (a/b)*b + a%b == a"2. In Python, "The floor division and modulo operators are connected by the following identity: x == (x//y)*y + (x%y)"3. So the rule for the quotient fixes the sign of the remainder.
Truncated division. C99 fixed the direction of /: before C99 the quotient was "rounded in implementation-defined direction", and since C99 it is "truncated towards zero"2. In C++, "the quotient is truncated towards zero (fractional part is discarded)"4. Java says: "Integer division rounds toward 0"5, and the remainder "can be negative only if the dividend is negative"5. Go uses the name "truncated division" in its specification and gives a table: -5 / 3 is -1 and -5 % 3 is -26. In C#, "The sign of the non-zero remainder matches the sign of the left-hand operand"7. Rust says: "Rust uses a remainder defined with truncating division."8
JavaScript. JavaScript numbers are floats, so / does not give a whole quotient. A program uses Math.trunc(a / b) or Math.floor(a / b). The % operator "always takes the sign of the dividend"9. MDN says: "Note that while in most languages, '%' is a remainder operator, in some (e.g., Python, Perl) it is a modulo operator."9
Floored division. Python's // applies the floor function to the result of the mathematical division3, and "The modulo operator always yields a result with the same sign as its second operand (or zero)"3. Java has Math.floorDiv and Math.floorMod. The floor modulus "has the same sign as the divisor y or is zero"10. CSS mod() is floored too: "It always takes the sign of the divisor."11
Euclidean division. The remainder is never negative. Rust's rem_euclid "Calculates the least nonnegative remainder of self when divided by rhs"12. This rule is useful for an index into a ring of n slots, because the result is always a valid index.
Division by zero and overflow. Integer division by zero is an error in most languages. Java throws an ArithmeticException when the divisor of an integer division or remainder is 05. In C, "If the second operand is zero, the behavior is undefined."2 The division of the most negative value by -1 overflows. Go defines the result: the quotient is the dividend itself, and the remainder is 0, "due to two's-complement integer overflow"6. See Integer overflow behaviour.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Idiom | |
| TypeScript | Idiom | TypeScript has the number type of JavaScript, so there is no integer division operator; a program uses Math.trunc or Math.floor, and % is truncated. No example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin / and % on integers truncate toward zero, rem is truncated, and mod is floored. No example file exists because kotlinc is not installed. |
| SQL | Native | SQL has MOD(x, y), which is truncated; the result of integer / integer depends on the database. No example file exists. |
| Bash | Native | Bash arithmetic has / and % on integers, which truncate toward zero as in the POSIX shell. No example file exists. |
| PowerShell | Idiom | PowerShell / gives a fraction when the division is not exact, so a script uses [Math]::Floor or [Math]::Truncate; % is truncated. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no arithmetic. |
| CSS | Native | CSS has the mod() function, which is floored, and the rem() function, which is truncated. No example file exists. |
| Regular expressions | Does not apply | A pattern matches digits as text but does no arithmetic. |
| Language | Verdict | Quotient and remainder |
|---|---|---|
| Python | native | // and % are floored; math.fmod is truncated |
| JavaScript | idiom | % is truncated; no integer /, so Math.trunc or Math.floor |
| TypeScript | idiom | as JavaScript |
| Java | native | / and % are truncated; Math.floorDiv and Math.floorMod |
| Kotlin | native | /, % and rem are truncated; mod is floored |
| C# | native | / and % are truncated; Math.DivRem |
| Go | native | / and % are truncated; big.Int Div and Mod are Euclidean |
| Rust | native | / and % are truncated; div_euclid and rem_euclid |
| C | native | / and % are truncated since C99; div |
| C++ | native | / and % are truncated; std::div |
| Bash | native | / and % in $(( )); the POSIX shell % is truncated |
| PowerShell | idiom | / can give a fraction; % is truncated; [Math]::Floor or [Math]::Truncate |
| SQL | native | MOD(x, y) is truncated |
| Regex | n/a | no arithmetic |
| HTML | n/a | no arithmetic |
| CSS | native | mod() is floored and rem() is truncated |
Wikipedia keeps a long table of the modulo operators of many languages, with the rule of each one1. In it, Kotlin's % and rem are truncated and mod is floored, PowerShell's % is truncated, the % of ksh is truncated "same as POSIX sh", and SQL mod(x,y) is truncated1. PowerShell's / gives a fraction when the division is not exact, and a cast of the result to [int] "rounds to the nearest even integer"13.
import math
print("-7 // 3:", -7 // 3)
print("-7 % 3:", -7 % 3)
print("divmod(-7, 3):", divmod(-7, 3))
print("7 % -3:", 7 % -3)
print("int(-7 / 3):", int(-7 / 3))
print("math.fmod(-7, 3):", math.fmod(-7, 3))
print("-7 is odd:", "yes" if -7 % 2 == 1 else "no")
try:
print(1 // 0)
except ZeroDivisionError as e:
print("1 // 0:", type(e).__name__)
-7 // 3: -3
-7 % 3: 2
divmod(-7, 3): (-3, 2)
7 % -3: -2
int(-7 / 3): -2
math.fmod(-7, 3): -1.0
-7 is odd: yes
1 // 0: ZeroDivisionError
- Verdict: native.
//and%use floored division, so the remainder has the sign of the divisor, anddivmodgives both results at once. int(-7 / 3)truncates a float quotient, andmath.fmodgives the truncated remainder as a float. For large integers,int(a / b)can be wrong, because/gives a float.- The test
n % 2 == 1works for negativenin Python, but not in the truncated languages.
#include <cstdlib>
#include <iostream>
int floor_mod(int a, int n) {
int r = a % n;
if (r != 0 && (r < 0) != (n < 0)) {
r += n;
}
return r;
}
int main() {
int a = -7;
int n = 3;
std::cout << "-7 / 3: " << a / n << '\n';
std::cout << "-7 % 3: " << a % n << '\n';
std::div_t d = std::div(a, n);
std::cout << "std::div(-7, 3): quot " << d.quot << ", rem " << d.rem << '\n';
std::cout << "floor_mod(-7, 3): " << floor_mod(a, n) << '\n';
std::cout << "floor_mod(7, -3): " << floor_mod(7, -3) << '\n';
}
-7 / 3: -2
-7 % 3: -1
std::div(-7, 3): quot -2, rem -1
floor_mod(-7, 3): 2
floor_mod(7, -3): -2
- Verdict: native.
/truncates toward zero, and%has the sign of the dividend.std::divgives both results. - The standard library has no floored remainder for integers, so a program writes a helper.
public class Main {
public static void main(String[] args) {
System.out.println("-7 / 3: " + -7 / 3);
System.out.println("-7 % 3: " + -7 % 3);
System.out.println("Math.floorDiv(-7, 3): " + Math.floorDiv(-7, 3));
System.out.println("Math.floorMod(-7, 3): " + Math.floorMod(-7, 3));
System.out.println("-7 % 2 == 1: " + (-7 % 2 == 1 ? "yes" : "no"));
System.out.println("Math.floorMod(-7, 2) == 1: " + (Math.floorMod(-7, 2) == 1 ? "yes" : "no"));
try {
int zero = 0;
System.out.println(1 / zero);
} catch (ArithmeticException e) {
System.out.println("1 / 0: " + e.getClass().getSimpleName());
}
}
}
-7 / 3: -2
-7 % 3: -1
Math.floorDiv(-7, 3): -3
Math.floorMod(-7, 3): 2
-7 % 2 == 1: no
Math.floorMod(-7, 2) == 1: yes
1 / 0: ArithmeticException
- Verdict: native.
/and%truncate toward zero, andMath.floorDivandMath.floorModgive the floored results. - Integer division by zero throws
ArithmeticException.
#include <stdio.h>
#include <stdlib.h>
static int floor_mod(int a, int n) {
int r = a % n;
if (r != 0 && (r < 0) != (n < 0)) {
r += n;
}
return r;
}
static int floor_div(int a, int n) {
int q = a / n;
if (a % n != 0 && (a < 0) != (n < 0)) {
q -= 1;
}
return q;
}
int main(void) {
int a = -7;
int n = 3;
printf("-7 / 3: %d\n", a / n);
printf("-7 %% 3: %d\n", a % n);
div_t d = div(a, n);
printf("div(-7, 3): quot %d, rem %d\n", d.quot, d.rem);
printf("floor_div(-7, 3): %d\n", floor_div(a, n));
printf("floor_mod(-7, 3): %d\n", floor_mod(a, n));
printf("-7 %% 2 == 1: %s\n", a % 2 == 1 ? "yes" : "no");
return 0;
}
-7 / 3: -2
-7 % 3: -1
div(-7, 3): quot -2, rem -1
floor_div(-7, 3): -3
floor_mod(-7, 3): 2
-7 % 2 == 1: no
- Verdict: native. Since C99,
/truncates toward zero and%has the sign of the dividend.divfrom<stdlib.h>gives both results in adiv_t. - The floored helpers correct the truncated result when the remainder is not zero and the signs differ.
- Division by zero is undefined behavior, so a program must test the divisor first.
using System;
static int FloorMod(int a, int n)
{
int r = a % n;
return r != 0 && (r < 0) != (n < 0) ? r + n : r;
}
Console.WriteLine($"-7 / 3: {-7 / 3}");
Console.WriteLine($"-7 % 3: {-7 % 3}");
var (q, r) = Math.DivRem(-7, 3);
Console.WriteLine($"Math.DivRem(-7, 3): ({q}, {r})");
Console.WriteLine($"FloorMod(-7, 3): {FloorMod(-7, 3)}");
Console.WriteLine($"5 % -4: {5 % -4}");
try
{
int zero = 0;
Console.WriteLine(1 / zero);
}
catch (DivideByZeroException e)
{
Console.WriteLine($"1 / 0: {e.GetType().Name}");
}
-7 / 3: -2
-7 % 3: -1
Math.DivRem(-7, 3): (-2, -1)
FloorMod(-7, 3): 2
5 % -4: 1
1 / 0: DivideByZeroException
- Verdict: native.
/truncates toward zero, and the remainder has the sign of the left operand.Math.DivRemreturns both results as a tuple. - Integer division by zero throws
DivideByZeroException.
const yesNo = (b) => (b ? "yes" : "no");
const floorMod = (a, n) => ((a % n) + n) % n;
console.log(`-7 / 3: ${-7 / 3}`);
console.log(`Math.trunc(-7 / 3): ${Math.trunc(-7 / 3)}`);
console.log(`Math.floor(-7 / 3): ${Math.floor(-7 / 3)}`);
console.log(`-7 % 3: ${-7 % 3}`);
console.log(`floorMod(-7, 3): ${floorMod(-7, 3)}`);
console.log(`-7n / 3n: ${-7n / 3n}`);
console.log(`-7 % 2 === 1: ${yesNo(-7 % 2 === 1)}`);
console.log(`-7 % 2 !== 0: ${yesNo(-7 % 2 !== 0)}`);
-7 / 3: -2.3333333333333335
Math.trunc(-7 / 3): -2
Math.floor(-7 / 3): -3
-7 % 3: -1
floorMod(-7, 3): 2
-7n / 3n: -2
-7 % 2 === 1: no
-7 % 2 !== 0: yes
- Verdict: idiom. JavaScript has no integer division for numbers, so a program uses
Math.truncorMath.flooron the float quotient.%is truncated, and a floored remainder needs a helper. BigIntdivision truncates toward zero.- The odd test
-7 % 2 === 1fails, because the remainder is -1.
package main
import (
"fmt"
"math/big"
)
func main() {
a, n := -7, 3
fmt.Println("-7 / 3:", a/n)
fmt.Println("-7 % 3:", a%n)
x, y := big.NewInt(-7), big.NewInt(3)
fmt.Println("big Div(-7, 3):", new(big.Int).Div(x, y))
fmt.Println("big Mod(-7, 3):", new(big.Int).Mod(x, y))
fmt.Println("big Quo(-7, 3):", new(big.Int).Quo(x, y))
fmt.Println("big Rem(-7, 3):", new(big.Int).Rem(x, y))
}
-7 / 3: -2
-7 % 3: -1
big Div(-7, 3): -3
big Mod(-7, 3): 2
big Quo(-7, 3): -2
big Rem(-7, 3): -1
- Verdict: native.
/truncates toward zero, and%has the sign of the dividend. Forbig.Int,DivandModare Euclidean, andQuoandRemare truncated. - An integer division by a zero variable panics at run time, and a division by a zero constant does not compile.
fn main() {
let a: i32 = -7;
println!("-7 / 3: {}", a / 3);
println!("-7 % 3: {}", a % 3);
println!("(-7).div_euclid(3): {}", a.div_euclid(3));
println!("(-7).rem_euclid(3): {}", a.rem_euclid(3));
println!("7.div_euclid(-3): {}", 7i32.div_euclid(-3));
println!("7.rem_euclid(-3): {}", 7i32.rem_euclid(-3));
println!("-7i32.rem_euclid(3): {}", -7i32.rem_euclid(3));
println!("(-7).checked_div(0): {:?}", a.checked_div(0));
}
-7 / 3: -2
-7 % 3: -1
(-7).div_euclid(3): -3
(-7).rem_euclid(3): 2
7.div_euclid(-3): -2
7.rem_euclid(-3): 1
-7i32.rem_euclid(3): -1
(-7).checked_div(0): None
- Verdict: native.
/and%truncate toward zero, anddiv_euclidandrem_euclidgive the Euclidean results, where the remainder is never negative. -7i32.rem_euclid(3)is -1, because the method call binds before the unary minus.- Division by zero panics, and
checked_divreturnsNoneinstead.
Variations and related ideas
- Rounded division. "Common Lisp and IEEE 754 use rounded division"1, where the quotient is rounded to the nearest integer. Python's
math.remainderfollows that rule1. - Ceiling division. "Common Lisp also uses ceiling division"1. A program that needs the number of pages for k items, p to a page, computes the ceiling of k / p, often as
(k + p - 1) / pfor positive values. - Floating-point remainder. Python's
math.fmodis truncated, and Python's%on floats is floored1. - Unsigned division. For unsigned values, the three rules give the same result.
Pitfalls
- An odd test with
%. Wikipedia: "to test if an integer is odd, one might be inclined to test if the remainder by 2 is equal to 1"1. With truncated division, "when n (the dividend) is negative and odd, n mod 2 returns −1, and the function returns false"1. Testn % 2 != 0instead. - A negative index.
i % ncan be negative in C, Java, JavaScript, C#, Go and Rust wheniis negative. Use a floored or Euclidean remainder, such asMath.floorModorrem_euclid, to get an index from 0 to n - 1. - Precedence in Rust.
-7i32.rem_euclid(3)is-(7i32.rem_euclid(3)), which is -1, because a method call binds more tightly than the unary minus. The Rust example shows this. Write(-7i32).rem_euclid(3). - Porting between languages. Code that moves from Python to C or Java, or back, changes its results for negative values without an error.
Cost
The truncated quotient and remainder come from the division of the hardware. A floored or Euclidean result needs one compare and one correction after that division, as the helper functions in the C, C++, C# and JavaScript examples show. For unsigned values, a division by a power of 2 is a right shift, and the remainder is a mask: x % 8 is x & 7.
History
C left the direction of signed division to the implementation until C99, which fixed it as truncation toward zero2. Knuth's The Art of Computer Programming promotes floored division1, and Boute's 1992 paper "The Euclidean definition of the functions div and mod" promotes the Euclidean rule1.
References
- Modulo, Wikipedia, the introduction; Variants of the definition; Common pitfalls; In programming languages
- Arithmetic operators, C reference, cppreference.com, Multiplicative operators; Remainder
- Expressions, The Python Language Reference, 6.7 Binary arithmetic operations
- Arithmetic operators, C++ reference, cppreference.com, Multiplicative operators
- The Java Language Specification, Java SE 27 Edition, Chapter 15: Expressions, 15.17.2 Division Operator /; 15.17.3 Remainder Operator %
- The Go Programming Language Specification, Integer operators
- Arithmetic operators, C# reference, Microsoft Learn, Remainder operator %, Integer remainder
- Operator expressions, The Rust Reference, Arithmetic and logical binary operators
- Remainder (%), MDN Web Docs, the introduction; Description
- Math, Java SE 27 API, floorDiv; floorMod
- mod(), CSS, MDN Web Docs, the introduction
- i32, Rust standard library, div_euclid; rem_euclid
- about_Arithmetic_Operators, PowerShell documentation, Microsoft Learn, Division and rounding
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 7YCVZD Edit this page History Report an error Markdown