142131Sbostic /* 242131Sbostic * Copyright (c) 1990 Regents of the University of California. 342131Sbostic * 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*48142Storek static char sccsid[] = "@(#)div.c 5.2 (Berkeley) 04/16/91"; 1342131Sbostic #endif /* LIBC_SCCS and not lint */ 1442131Sbostic 1542131Sbostic #include <stdlib.h> /* div_t */ 1642131Sbostic 1742131Sbostic div_t 1842131Sbostic div(num, denom) 1942131Sbostic int num, denom; 2042131Sbostic { 2142131Sbostic div_t r; 2242131Sbostic 2342131Sbostic r.quot = num / denom; 2442131Sbostic r.rem = num % denom; 25*48142Storek /* 26*48142Storek * The ANSI standard says that |r.quot| <= |n/d|, where 27*48142Storek * n/d is to be computed in infinite precision. In other 28*48142Storek * words, we should always truncate the quotient towards 29*48142Storek * 0, never -infinity. 30*48142Storek * 31*48142Storek * Machine division and remainer may work either way when 32*48142Storek * one or both of n or d is negative. If only one is 33*48142Storek * negative and r.quot has been truncated towards -inf, 34*48142Storek * r.rem will have the same sign as denom and the opposite 35*48142Storek * sign of num; if both are negative and r.quot has been 36*48142Storek * truncated towards -inf, r.rem will be positive (will 37*48142Storek * have the opposite sign of num). These are considered 38*48142Storek * `wrong'. 39*48142Storek * 40*48142Storek * If both are num and denom are positive, r will always 41*48142Storek * be positive. 42*48142Storek * 43*48142Storek * This all boils down to: 44*48142Storek * if num >= 0, but r.rem < 0, we got the wrong answer. 45*48142Storek * In that case, to get the right answer, add 1 to r.quot and 46*48142Storek * subtract denom from r.rem. 47*48142Storek */ 48*48142Storek if (num >= 0 && r.rem < 0) { 49*48142Storek r.quot++; 50*48142Storek r.rem -= denom; 5142131Sbostic } 5242131Sbostic return (r); 5342131Sbostic } 54