div() & ldiv() behavior?

D'Arcy J.M. Cain darcy at druid.uucp
Thu Apr 11 04:19:21 AEST 1991


In article <10989 at ncar.ucar.edu> Steve Emmerson writes:
>Would someone who knows please tell me the behavior of div() and ldiv()?
>[...]
>I know what this means when both arguments are positive, but I'm uncertain
>what this means for the other three cases.  I you would tell me, I would
>appreciate it.

I happened to have given this some thought recently and although there
doesn't seem to be any standard mandated behaviour as far as I can tell
here is what I came up with in an implementation:

--------------------------- start of div.c ----------------------------
/*
 * div.c
 * Written by D'Arcy J.M. Cain
 * note LDIV_SUB defined turns this into ldiv()
 *
 * This is part of my effort to collect all the routines that
 * comprise the ANSI standard library in one place.  These routines
 * are public domain unless specifically stated otherwise in a
 * source file.
 */

/*
What does div and ldiv do with negative numbers?  Working backwards from
the observation that when positive numbers are involved, the remainder
added to the product of the quotient and denominator should give the
numerator, I get the following examples:

    num   denom    quot    rem
    ===   =====    ====    ===
    +13      +5      +2     +3
    -13      +5      -2     -3
    +13      -5      -2     +3
    -13      -5      +2     -3

if denom is 0 then I return qotient as 0 and remainder as the numerator.
That seems to fit the model: (0 * 0) + rem == num.

*/

#include <stdlib.h>

#ifdef	LDIV_SUB
ldiv_t	ldiv(long num, long denom)
{
	ldiv_t r;
#else
div_t	div(int num, int denom)
{
	div_t r;
#endif	/* LDIV_SUB */

	int sr, sq;

	if (!denom)
	{
		r.quot = 0;
		r.rem = num;
		return(r);
	}

	if (num < 0)
	{
		sr = -1;
		num = -num;
	}
	else
		sr = 1;

	if (denom < 0)
	{
		sq = sr * -1;
		denom = -denom;
	}
	else
		sq = sr;

	r.quot = num / denom * sq;
	r.rem = (num % denom) * sr;
	return (r);
}
------------------------------------------------------------------------

Hope this helps.

-- 
D'Arcy J.M. Cain (darcy at druid)     |
D'Arcy Cain Consulting             |   There's no government
Toronto, Ontario, Canada           |   like no government!
+1 416 424 2871                    |



More information about the Comp.std.c mailing list