ldiv.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 Library General Public License as
  5. published by the Free Software Foundation; either version 2 of the
  6. 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. Library General Public License for more details.
  11. You should have received a copy of the GNU Library General Public
  12. License along with the GNU C Library; see the file COPYING.LIB. If not,
  13. write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  14. Boston, MA 02111-1307, USA. */
  15. typedef struct {
  16. long quot;
  17. long rem;
  18. } ldiv_t;
  19. /* Return the `ldiv_t' representation of NUMER over DENOM. */
  20. ldiv_t
  21. ldiv (long int numer, long int denom)
  22. {
  23. ldiv_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. }