1 /* 2 * Copyright (c) 1990, 1993 3 * The Regents of the University of California. All rights reserved. 4 * 5 * This code is derived from software contributed to Berkeley by 6 * Chris Torek. 7 * 8 * %sccs.include.redist.c% 9 */ 10 11 #if defined(LIBC_SCCS) && !defined(lint) 12 static char sccsid[] = "@(#)div.c 8.1 (Berkeley) 06/04/93"; 13 #endif /* LIBC_SCCS and not lint */ 14 15 #include <stdlib.h> /* div_t */ 16 17 div_t 18 div(num, denom) 19 int num, denom; 20 { 21 div_t r; 22 23 r.quot = num / denom; 24 r.rem = num % denom; 25 /* 26 * The ANSI standard says that |r.quot| <= |n/d|, where 27 * n/d is to be computed in infinite precision. In other 28 * words, we should always truncate the quotient towards 29 * 0, never -infinity. 30 * 31 * Machine division and remainer may work either way when 32 * one or both of n or d is negative. If only one is 33 * negative and r.quot has been truncated towards -inf, 34 * r.rem will have the same sign as denom and the opposite 35 * sign of num; if both are negative and r.quot has been 36 * truncated towards -inf, r.rem will be positive (will 37 * have the opposite sign of num). These are considered 38 * `wrong'. 39 * 40 * If both are num and denom are positive, r will always 41 * be positive. 42 * 43 * This all boils down to: 44 * if num >= 0, but r.rem < 0, we got the wrong answer. 45 * In that case, to get the right answer, add 1 to r.quot and 46 * subtract denom from r.rem. 47 */ 48 if (num >= 0 && r.rem < 0) { 49 r.quot++; 50 r.rem -= denom; 51 } 52 return (r); 53 } 54