This guide demonstrates integer division using the pairs of built-in functions
div()
&
mod()
,
and
quo()
&
rem()
.
When used with two integers where one divides the other evenly
the div()
and quo()
functions behave identically, and
the mod()
and rem()
functions return zero:
no-remainder.cue
// 15 divides 3 evenly, leaving no remainder.
quotient: div(15, 3) & quo(15, 3)
remainder: mod(15, 3) & rem(15, 3)
TERMINAL
$ cue eval no-remainder.cue
quotient: 5
remainder: 0
The div()
and mod()
functions implement
Euclidean division,
which behaves as follows when used with integers that don’t divide evenly
(leaving a non-zero remainder):
euclidean.cue
// div() and mod() implement Euclidean division.
"div(15, 4)": div(15, 4)
"mod(15, 4)": mod(15, 4)
"div(15, -4)": div(15, -4)
"mod(15, -4)": mod(15, -4)
"div(-15, 4)": div(-15, 4)
"mod(-15, 4)": mod(-15, 4)
"div(-15, -4)": div(-15, -4)
"mod(-15, -4)": mod(-15, -4)
TERMINAL
$ cue eval euclidean.cue
"div(15, 4)": 3
"mod(15, 4)": 3
"div(15, -4)": -3
"mod(15, -4)": 3
"div(-15, 4)": -4
"mod(-15, 4)": 1
"div(-15, -4)": 4
"mod(-15, -4)": 1
The quo()
and rem()
functions implement truncated division,
with quo()
’s value being truncated towards zero:
truncated.cue
// quo() and rem() implement truncated division.
"quo(15, 4)": quo(15, 4)
"rem(15, 4)": rem(15, 4)
"quo(15, -4)": quo(15, -4)
"rem(15, -4)": rem(15, -4)
"quo(-15, 4)": quo(-15, 4)
"rem(-15, 4)": rem(-15, 4)
"quo(-15, -4)": quo(-15, -4)
"rem(-15, -4)": rem(-15, -4)
TERMINAL
$ cue eval truncated.cue
"quo(15, 4)": 3
"rem(15, 4)": 3
"quo(15, -4)": -3
"rem(15, -4)": 3
"quo(-15, 4)": -3
"rem(-15, 4)": -3
"quo(-15, -4)": 3
"rem(-15, -4)": -3
Related content
- The behaviours of the integer divison functions are defined in The CUE Language Specification