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