lh | 9ed821d | 2023-04-07 01:36:19 -0700 | [diff] [blame] | 1 | /* `long long int' divison with remainder. |
| 2 | Copyright (C) 1992, 1996, 1997 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, write to the Free |
| 17 | Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA |
| 18 | 02111-1307 USA. */ |
| 19 | |
| 20 | #include <features.h> |
| 21 | #include <stdlib.h> |
| 22 | |
| 23 | |
| 24 | /* Return the `lldiv_t' representation of NUMER over DENOM. */ |
| 25 | lldiv_t |
| 26 | lldiv (long long int numer, 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 | } |
| 57 | |
| 58 | #if __WORDSIZE != 64 |
| 59 | #undef imaxdiv |
| 60 | strong_alias(lldiv,imaxdiv) |
| 61 | #endif |