1 /* Copyright (C) 1992, 1997 Free Software Foundation, Inc. 2 This file is part of the GNU C Library. 3 4 * SPDX-License-Identifier: LGPL-2.0+ 5 */ 6 7 typedef struct { 8 long quot; 9 long rem; 10 } ldiv_t; 11 /* Return the `ldiv_t' representation of NUMER over DENOM. */ 12 ldiv_t 13 ldiv (long int numer, long int denom) 14 { 15 ldiv_t result; 16 17 result.quot = numer / denom; 18 result.rem = numer % denom; 19 20 /* The ANSI standard says that |QUOT| <= |NUMER / DENOM|, where 21 NUMER / DENOM is to be computed in infinite precision. In 22 other words, we should always truncate the quotient towards 23 zero, never -infinity. Machine division and remainer may 24 work either way when one or both of NUMER or DENOM is 25 negative. If only one is negative and QUOT has been 26 truncated towards -infinity, REM will have the same sign as 27 DENOM and the opposite sign of NUMER; if both are negative 28 and QUOT has been truncated towards -infinity, REM will be 29 positive (will have the opposite sign of NUMER). These are 30 considered `wrong'. If both are NUM and DENOM are positive, 31 RESULT will always be positive. This all boils down to: if 32 NUMER >= 0, but REM < 0, we got the wrong answer. In that 33 case, to get the right answer, add 1 to QUOT and subtract 34 DENOM from REM. */ 35 36 if (numer >= 0 && result.rem < 0) 37 { 38 ++result.quot; 39 result.rem -= denom; 40 } 41 42 return result; 43 } 44