ldiv.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /* Copyright (C) 1992, 1997 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. */
  5. typedef struct {
  6. long quot;
  7. long rem;
  8. } ldiv_t;
  9. /* Return the `ldiv_t' representation of NUMER over DENOM. */
  10. ldiv_t
  11. ldiv (long int numer, long int denom)
  12. {
  13. ldiv_t result;
  14. result.quot = numer / denom;
  15. result.rem = numer % denom;
  16. /* The ANSI standard says that |QUOT| <= |NUMER / DENOM|, where
  17. NUMER / DENOM is to be computed in infinite precision. In
  18. other words, we should always truncate the quotient towards
  19. zero, never -infinity. Machine division and remainer may
  20. work either way when one or both of NUMER or DENOM is
  21. negative. If only one is negative and QUOT has been
  22. truncated towards -infinity, REM will have the same sign as
  23. DENOM and the opposite sign of NUMER; if both are negative
  24. and QUOT has been truncated towards -infinity, REM will be
  25. positive (will have the opposite sign of NUMER). These are
  26. considered `wrong'. If both are NUM and DENOM are positive,
  27. RESULT will always be positive. This all boils down to: if
  28. NUMER >= 0, but REM < 0, we got the wrong answer. In that
  29. case, to get the right answer, add 1 to QUOT and subtract
  30. DENOM from REM. */
  31. if (numer >= 0 && result.rem < 0)
  32. {
  33. ++result.quot;
  34. result.rem -= denom;
  35. }
  36. return result;
  37. }