Back to index

glibc  2.9
lldiv.c
Go to the documentation of this file.
00001 /* `long long int' divison with remainder.
00002    Copyright (C) 1992, 1996, 1997 Free Software Foundation, Inc.
00003    This file is part of the GNU C Library.
00004 
00005    The GNU C Library is free software; you can redistribute it and/or
00006    modify it under the terms of the GNU Lesser General Public
00007    License as published by the Free Software Foundation; either
00008    version 2.1 of the License, or (at your option) any later version.
00009 
00010    The GNU C Library is distributed in the hope that it will be useful,
00011    but WITHOUT ANY WARRANTY; without even the implied warranty of
00012    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00013    Lesser General Public License for more details.
00014 
00015    You should have received a copy of the GNU Lesser General Public
00016    License along with the GNU C Library; if not, write to the Free
00017    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
00018    02111-1307 USA.  */
00019 
00020 #include <stdlib.h>
00021 
00022 
00023 /* Return the `lldiv_t' representation of NUMER over DENOM.  */
00024 lldiv_t
00025 lldiv (numer, denom)
00026      long long int numer;
00027      long long int denom;
00028 {
00029   lldiv_t result;
00030 
00031   result.quot = numer / denom;
00032   result.rem = numer % denom;
00033 
00034   /* The ANSI standard says that |QUOT| <= |NUMER / DENOM|, where
00035      NUMER / DENOM is to be computed in infinite precision.  In
00036      other words, we should always truncate the quotient towards
00037      zero, never -infinity.  Machine division and remainer may
00038      work either way when one or both of NUMER or DENOM is
00039      negative.  If only one is negative and QUOT has been
00040      truncated towards -infinity, REM will have the same sign as
00041      DENOM and the opposite sign of NUMER; if both are negative
00042      and QUOT has been truncated towards -infinity, REM will be
00043      positive (will have the opposite sign of NUMER).  These are
00044      considered `wrong'.  If both are NUM and DENOM are positive,
00045      RESULT will always be positive.  This all boils down to: if
00046      NUMER >= 0, but REM < 0, we got the wrong answer.  In that
00047      case, to get the right answer, add 1 to QUOT and subtract
00048      DENOM from REM.  */
00049 
00050   if (numer >= 0 && result.rem < 0)
00051     {
00052       ++result.quot;
00053       result.rem -= denom;
00054     }
00055 
00056   return result;
00057 }