]> git.ipfire.org Git - thirdparty/glibc.git/blob - stdlib/lldiv.c
Update copyright notices with scripts/update-copyrights.
[thirdparty/glibc.git] / stdlib / lldiv.c
1 /* `long long int' divison with remainder.
2 Copyright (C) 1992-2013 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <http://www.gnu.org/licenses/>. */
18
19 #include <stdlib.h>
20
21
22 /* Return the `lldiv_t' representation of NUMER over DENOM. */
23 lldiv_t
24 lldiv (numer, denom)
25 long long int numer;
26 long long int denom;
27 {
28 lldiv_t result;
29
30 result.quot = numer / denom;
31 result.rem = numer % denom;
32
33 /* The ANSI standard says that |QUOT| <= |NUMER / DENOM|, where
34 NUMER / DENOM is to be computed in infinite precision. In
35 other words, we should always truncate the quotient towards
36 zero, never -infinity. Machine division and remainer may
37 work either way when one or both of NUMER or DENOM is
38 negative. If only one is negative and QUOT has been
39 truncated towards -infinity, REM will have the same sign as
40 DENOM and the opposite sign of NUMER; if both are negative
41 and QUOT has been truncated towards -infinity, REM will be
42 positive (will have the opposite sign of NUMER). These are
43 considered `wrong'. If both are NUM and DENOM are positive,
44 RESULT will always be positive. This all boils down to: if
45 NUMER >= 0, but REM < 0, we got the wrong answer. In that
46 case, to get the right answer, add 1 to QUOT and subtract
47 DENOM from REM. */
48
49 if (numer >= 0 && result.rem < 0)
50 {
51 ++result.quot;
52 result.rem -= denom;
53 }
54
55 return result;
56 }