xref: /csrg-svn/lib/libc/stdlib/div.c (revision 61180)
142131Sbostic /*
2*61180Sbostic  * Copyright (c) 1990, 1993
3*61180Sbostic  *	The Regents of the University of California.  All rights reserved.
442131Sbostic  *
542131Sbostic  * This code is derived from software contributed to Berkeley by
642131Sbostic  * Chris Torek.
742131Sbostic  *
842131Sbostic  * %sccs.include.redist.c%
942131Sbostic  */
1042131Sbostic 
1142131Sbostic #if defined(LIBC_SCCS) && !defined(lint)
12*61180Sbostic static char sccsid[] = "@(#)div.c	8.1 (Berkeley) 06/04/93";
1342131Sbostic #endif /* LIBC_SCCS and not lint */
1442131Sbostic 
1542131Sbostic #include <stdlib.h>		/* div_t */
1642131Sbostic 
1742131Sbostic div_t
div(num,denom)1842131Sbostic div(num, denom)
1942131Sbostic 	int num, denom;
2042131Sbostic {
2142131Sbostic 	div_t r;
2242131Sbostic 
2342131Sbostic 	r.quot = num / denom;
2442131Sbostic 	r.rem = num % denom;
2548142Storek 	/*
2648142Storek 	 * The ANSI standard says that |r.quot| <= |n/d|, where
2748142Storek 	 * n/d is to be computed in infinite precision.  In other
2848142Storek 	 * words, we should always truncate the quotient towards
2948142Storek 	 * 0, never -infinity.
3048142Storek 	 *
3148142Storek 	 * Machine division and remainer may work either way when
3248142Storek 	 * one or both of n or d is negative.  If only one is
3348142Storek 	 * negative and r.quot has been truncated towards -inf,
3448142Storek 	 * r.rem will have the same sign as denom and the opposite
3548142Storek 	 * sign of num; if both are negative and r.quot has been
3648142Storek 	 * truncated towards -inf, r.rem will be positive (will
3748142Storek 	 * have the opposite sign of num).  These are considered
3848142Storek 	 * `wrong'.
3948142Storek 	 *
4048142Storek 	 * If both are num and denom are positive, r will always
4148142Storek 	 * be positive.
4248142Storek 	 *
4348142Storek 	 * This all boils down to:
4448142Storek 	 *	if num >= 0, but r.rem < 0, we got the wrong answer.
4548142Storek 	 * In that case, to get the right answer, add 1 to r.quot and
4648142Storek 	 * subtract denom from r.rem.
4748142Storek 	 */
4848142Storek 	if (num >= 0 && r.rem < 0) {
4948142Storek 		r.quot++;
5048142Storek 		r.rem -= denom;
5142131Sbostic 	}
5242131Sbostic 	return (r);
5342131Sbostic }
54