Programming Search⌘K

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_euclid and rem_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}")
Output
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

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptIdiom
TypeScriptIdiomTypeScript 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.
GoNative
RustNative
KotlinNativeKotlin / and % on integers truncate toward zero, rem is truncated, and mod is floored. No example file exists because kotlinc is not installed.
SQLNativeSQL has MOD(x, y), which is truncated; the result of integer / integer depends on the database. No example file exists.
BashNativeBash arithmetic has / and % on integers, which truncate toward zero as in the POSIX shell. No example file exists.
PowerShellIdiomPowerShell / 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.
HTMLDoes not applyHTML has no arithmetic.
CSSNativeCSS has the mod() function, which is floored, and the rem() function, which is truncated. No example file exists.
Regular expressionsDoes not applyA 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.

PythonGitHub
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__)
Output
-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, and divmod gives both results at once.
  • int(-7 / 3) truncates a float quotient, and math.fmod gives the truncated remainder as a float. For large integers, int(a / b) can be wrong, because / gives a float.
  • The test n % 2 == 1 works for negative n in 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';
}
Output
-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::div gives both results.
  • The standard library has no floored remainder for integers, so a program writes a helper.
JavaGitHub
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());
    }
  }
}
Output
-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, and Math.floorDiv and Math.floorMod give 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;
}
Output
-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. div from <stdlib.h> gives both results in a div_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}");
}
Output
-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.DivRem returns both results as a tuple.
  • Integer division by zero throws DivideByZeroException.
JavaScriptGitHub
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)}`);
Output
-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.trunc or Math.floor on the float quotient. % is truncated, and a floored remainder needs a helper.
  • BigInt division truncates toward zero.
  • The odd test -7 % 2 === 1 fails, 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))
}
Output
-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. For big.Int, Div and Mod are Euclidean, and Quo and Rem are truncated.
  • An integer division by a zero variable panics at run time, and a division by a zero constant does not compile.
RustGitHub
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));
}
Output
-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, and div_euclid and rem_euclid give 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_div returns None instead.
  • Rounded division. "Common Lisp and IEEE 754 use rounded division"1, where the quotient is rounded to the nearest integer. Python's math.remainder follows 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) / p for positive values.
  • Floating-point remainder. Python's math.fmod is 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. Test n % 2 != 0 instead.
  • A negative index. i % n can be negative in C, Java, JavaScript, C#, Go and Rust when i is negative. Use a floored or Euclidean remainder, such as Math.floorMod or rem_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

  1. Modulo, Wikipedia, the introduction; Variants of the definition; Common pitfalls; In programming languages
  2. Arithmetic operators, C reference, cppreference.com, Multiplicative operators; Remainder
  3. Expressions, The Python Language Reference, 6.7 Binary arithmetic operations
  4. Arithmetic operators, C++ reference, cppreference.com, Multiplicative operators
  5. The Java Language Specification, Java SE 27 Edition, Chapter 15: Expressions, 15.17.2 Division Operator /; 15.17.3 Remainder Operator %
  6. The Go Programming Language Specification, Integer operators
  7. Arithmetic operators, C# reference, Microsoft Learn, Remainder operator %, Integer remainder
  8. Operator expressions, The Rust Reference, Arithmetic and logical binary operators
  9. Remainder (%), MDN Web Docs, the introduction; Description
  10. Math, Java SE 27 API, floorDiv; floorMod
  11. mod(), CSS, MDN Web Docs, the introduction
  12. i32, Rust standard library, div_euclid; rem_euclid
  13. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/7YCVZD/text.yaml