mod, rem
mod, rem Function
Syntax:
mod number divisor → modulus
rem number divisor → remainder
Arguments and Values:
number—a real.
divisor—a real.
modulus, remainder—a real.
Description:
mod and rem are generalizations of the modulus and remainder functions respectively.
mod performs the operation floor on number and divisor and returns the remainder of the floor operation.
rem performs the operation truncate on number and divisor and returns the remainder of the truncate operation.
mod and rem are the modulus and remainder functions when number and divisor are integers.
Examples:
(rem -1 5) → -1
(mod -1 5) → 4
(mod 13 4) → 1
(rem 13 4) → 1
(mod -13 4) → 3
(rem -13 4) → -1
(mod 13 -4) → -3
(rem 13 -4) → 1
(mod -13 -4) → -1
(rem -13 -4) → -1
(mod 13.4 1) → 0.4
(rem 13.4 1) → 0.4
(mod -13.4 1) → 0.6
(rem -13.4 1) → -0.4
See Also:
floor, truncate
Notes:
The result of mod is either zero or a real with the same sign as divisor.
Expanded Reference: mod, rem
Basic modulus and remainder
mod returns the remainder from floor division. rem returns the remainder from truncate division. They agree when both arguments have the same sign.
(mod 13 4)
=> 1
(rem 13 4)
=> 1
(mod 10 3)
=> 1
(rem 10 3)
=> 1
Difference with negative arguments
mod and rem differ when the arguments have different signs. mod always returns a result with the same sign as the divisor. rem always returns a result with the same sign as the dividend.
(mod -1 5)
=> 4
(rem -1 5)
=> -1
(mod -13 4)
=> 3
(rem -13 4)
=> -1
(mod 13 -4)
=> -3
(rem 13 -4)
=> 1
(mod -13 -4)
=> -1
(rem -13 -4)
=> -1
Floating-point arguments
mod and rem work with floating-point numbers as well.
(mod 13.4 1)
=> 0.39999962
(rem 13.4 1)
=> 0.39999962
(mod -13.4 1)
=> 0.6000004
(rem -13.4 1)
=> -0.39999962
Testing divisibility
mod (or rem) with a result of zero means the dividend is evenly divisible by the divisor.
(zerop (mod 12 3))
=> T
(zerop (mod 12 5))
=> NIL
Cyclic indexing
mod is commonly used to wrap an index around within a fixed range.
(defun cyclic-index (i n)
(mod i n))
(cyclic-index 7 5)
=> 2
(cyclic-index -1 5)
=> 4
(cyclic-index 5 5)
=> 0