lldiv.c 2.3 KB

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