Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Division Semantics

BigInt supports two division conventions:

NameOperator / MethodQuotientPython equivalent
Floor division//, %, divmod()Toward −∞//, %
Truncate division/, .truncate_divide(), .truncate_modulo()Toward zeroC/Java /, %

/ on a BInt is integer division, not a promotion to a decimal type. It follows Mojo’s own Int, where Int(7) / Int(-2) is -3: the quotient stays in the type and rounds toward zero. It is therefore a different operator from //, not a synonym, and the two disagree exactly when the operands have opposite signs.

The difference matters for negative operands:

var a = BInt(7)
var b = BInt(-2)

# Floor division (Python semantics)
print(a // b)                    # -4
print(a % b)                     # -1

# Truncate division (C/Java semantics)
print(a / b)                     # -3
print(a.truncate_divide(b))      # -3
print(a.truncate_modulo(b))      #  1