github.com/aergoio/aergo@v1.3.1/libtool/src/gmp-6.1.2/mpz/divexact.c (about)

     1  /* mpz_divexact -- finds quotient when known that quot * den == num && den != 0.
     2  
     3  Contributed to the GNU project by Niels Möller.
     4  
     5  Copyright 1991, 1993-1998, 2000-2002, 2005-2007, 2009, 2012 Free Software
     6  Foundation, Inc.
     7  
     8  This file is part of the GNU MP Library.
     9  
    10  The GNU MP Library is free software; you can redistribute it and/or modify
    11  it under the terms of either:
    12  
    13    * the GNU Lesser General Public License as published by the Free
    14      Software Foundation; either version 3 of the License, or (at your
    15      option) any later version.
    16  
    17  or
    18  
    19    * the GNU General Public License as published by the Free Software
    20      Foundation; either version 2 of the License, or (at your option) any
    21      later version.
    22  
    23  or both in parallel, as here.
    24  
    25  The GNU MP Library is distributed in the hope that it will be useful, but
    26  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
    27  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    28  for more details.
    29  
    30  You should have received copies of the GNU General Public License and the
    31  GNU Lesser General Public License along with the GNU MP Library.  If not,
    32  see https://www.gnu.org/licenses/.  */
    33  
    34  
    35  #include "gmp.h"
    36  #include "gmp-impl.h"
    37  #include "longlong.h"
    38  
    39  void
    40  mpz_divexact (mpz_ptr quot, mpz_srcptr num, mpz_srcptr den)
    41  {
    42    mp_ptr qp;
    43    mp_size_t qn;
    44    mp_srcptr np, dp;
    45    mp_size_t nn, dn;
    46    TMP_DECL;
    47  
    48  #if WANT_ASSERT
    49    {
    50      mpz_t  rem;
    51      mpz_init (rem);
    52      mpz_tdiv_r (rem, num, den);
    53      ASSERT (SIZ(rem) == 0);
    54      mpz_clear (rem);
    55    }
    56  #endif
    57  
    58    nn = ABSIZ (num);
    59    dn = ABSIZ (den);
    60  
    61    if (nn < dn)
    62      {
    63        /* This special case avoids segfaults below when the function is
    64  	 incorrectly called with |N| < |D|, N != 0.  It also handles the
    65  	 well-defined case N = 0.  */
    66        SIZ(quot) = 0;
    67        return;
    68      }
    69  
    70    qn = nn - dn + 1;
    71  
    72    TMP_MARK;
    73  
    74    if (quot == num || quot == den)
    75      qp = TMP_ALLOC_LIMBS (qn);
    76    else
    77      qp = MPZ_REALLOC (quot, qn);
    78  
    79    np = PTR(num);
    80    dp = PTR(den);
    81  
    82    mpn_divexact (qp, np, nn, dp, dn);
    83    MPN_NORMALIZE (qp, qn);
    84  
    85    if (qp != PTR(quot))
    86      MPN_COPY (MPZ_REALLOC (quot, qn), qp, qn);
    87  
    88    SIZ(quot) = (SIZ(num) ^ SIZ(den)) >= 0 ? qn : -qn;
    89  
    90    TMP_FREE;
    91  }