ldiv.c 2.1 KB

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