1 /* imaxdiv() function: division of 'intmax_t'.
2 Copyright (C) 2006 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
26 imaxdiv (intmax_t numer, intmax_t denom)
30 result.quot = numer / denom;
31 result.rem = numer % denom;
33 /* Verify the requirements of ISO C 99 section 6.5.5 paragraph 6:
34 "When integers are divided, the result of the / operator is the
35 algebraic quotient with any fractional part discarded. (This is
36 often called "truncation toward zero".) If the quotient a/b is
37 representable, the expression (a/b)*b + a%b shall equal a." */
39 || (INTMAX_MIN + INTMAX_MAX < 0
41 && numer < - INTMAX_MAX)))
43 if (!(result.quot * denom + result.rem == numer))
44 /* The compiler's implementation of / and % is broken. */
50 : /* Don't write result.rem < - denom,
51 as it gives integer overflow if denom == INTMAX_MIN. */
55 ? result.rem > - denom
56 : result.rem > denom)))
57 /* The compiler's implementation of / and % may be ok according to
58 C89, but not to C99. Please report this to <bug-gnulib@ngu.org>.
59 This might be a big portability problem. */