lldiv.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, write to the Free
  14. Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  15. 02111-1307 USA. */
  16. #include <features.h>
  17. #include <stdlib.h>
  18. /* Return the `lldiv_t' representation of NUMER over DENOM. */
  19. lldiv_t
  20. lldiv (long long int numer, long long int denom)
  21. {
  22. lldiv_t result;
  23. result.quot = numer / denom;
  24. result.rem = numer % denom;
  25. /* The ANSI standard says that |QUOT| <= |NUMER / DENOM|, where
  26. NUMER / DENOM is to be computed in infinite precision. In
  27. other words, we should always truncate the quotient towards
  28. zero, never -infinity. Machine division and remainer may
  29. work either way when one or both of NUMER or DENOM is
  30. negative. If only one is negative and QUOT has been
  31. truncated towards -infinity, REM will have the same sign as
  32. DENOM and the opposite sign of NUMER; if both are negative
  33. and QUOT has been truncated towards -infinity, REM will be
  34. positive (will have the opposite sign of NUMER). These are
  35. considered `wrong'. If both are NUM and DENOM are positive,
  36. RESULT will always be positive. This all boils down to: if
  37. NUMER >= 0, but REM < 0, we got the wrong answer. In that
  38. case, to get the right answer, add 1 to QUOT and subtract
  39. DENOM from REM. */
  40. if (numer >= 0 && result.rem < 0)
  41. {
  42. ++result.quot;
  43. result.rem -= denom;
  44. }
  45. return result;
  46. }
  47. #if __WORDSIZE != 64
  48. #undef imaxdiv
  49. strong_alias(lldiv,imaxdiv)
  50. #endif