Integer division

Earl Killian earl at mips.UUCP
Fri Feb 7 07:03:42 AEST 1986


Of the languages I'm familiar with, I believe integer division is
best handled in Common Lisp.  There are four functions of two
arguments: trunc, floor, ceil, and round.  Each divides the first
argument by the second and then rounds the result to an integer
using round to zero, round to -infinity, round to +infinity, and
round to nearest respectively.  The second return value is the
remainder of that division.

Thus:
(trunc 7 3)	=>  2,  1		; 2*3 + 1 = 7
(trunc -7 3)	=> -2, -1		; -2*3 + -1 = -7
(floor 7 3)	=>  2,  1		; 2*3 + 1 = 7
(floor -7 3)	=> -3,  2		; -3*3 + 2 = -7
(ceil 7 3)	=> 3, -2		; 3*3 + -2 = 7
(ceil -7 3)	=> -2, -1		; -2*3 + -1 = -7
(round 7 3)	=> 2, 1			; 2*3 + 1 = 7
(round -7 3)	=> -2, -1		; -2*3 + -1 = -7

The programmer picks what is appropriate.  I have found floor and ceil
to be the most useful, and trunc somewhat less.  I have never used round.

Actually these are also functions of one argument: (floor 3.5) => 3 0.5,
etc.



More information about the Comp.lang.c mailing list