blob: 8e11333acdf391cd9113afa62e2ba6cce8d9ccfb [file] [log] [blame]
wdenk4a5b6a32001-04-28 17:59:11 +00001/* Copyright (C) 1992, 1997 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3
Wolfgang Denka53002f2013-07-08 11:58:49 +02004 * SPDX-License-Identifier: LGPL-2.0+
5 */
wdenk4a5b6a32001-04-28 17:59:11 +00006
7typedef struct {
wdenk8bde7f72003-06-27 21:31:46 +00008 long quot;
9 long rem;
wdenk4a5b6a32001-04-28 17:59:11 +000010} ldiv_t;
11/* Return the `ldiv_t' representation of NUMER over DENOM. */
12ldiv_t
13ldiv (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}