lldiv.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include <features.h>
  16. #include <stdlib.h>
  17. /* Return the `lldiv_t' representation of NUMER over DENOM. */
  18. lldiv_t
  19. lldiv (long long int numer, long long int denom)
  20. {
  21. lldiv_t result;
  22. result.quot = numer / denom;
  23. result.rem = numer % denom;
  24. /* The ANSI standard says that |QUOT| <= |NUMER / DENOM|, where
  25. NUMER / DENOM is to be computed in infinite precision. In
  26. other words, we should always truncate the quotient towards
  27. zero, never -infinity. Machine division and remainer may
  28. work either way when one or both of NUMER or DENOM is
  29. negative. If only one is negative and QUOT has been
  30. truncated towards -infinity, REM will have the same sign as
  31. DENOM and the opposite sign of NUMER; if both are negative
  32. and QUOT has been truncated towards -infinity, REM will be
  33. positive (will have the opposite sign of NUMER). These are
  34. considered `wrong'. If both are NUM and DENOM are positive,
  35. RESULT will always be positive. This all boils down to: if
  36. NUMER >= 0, but REM < 0, we got the wrong answer. In that
  37. case, to get the right answer, add 1 to QUOT and subtract
  38. DENOM from REM. */
  39. if (numer >= 0 && result.rem < 0)
  40. {
  41. ++result.quot;
  42. result.rem -= denom;
  43. }
  44. return result;
  45. }
  46. #if __WORDSIZE != 64
  47. #undef imaxdiv
  48. strong_alias(lldiv,imaxdiv)
  49. #endif