tdiv_r.c
Upload User: qaz666999
Upload Date: 2022-08-06
Package Size: 2570k
Code Size: 2k
Category:

Algorithm

Development Platform:

Unix_Linux

  1. /* mpz_tdiv_r(rem, dividend, divisor) -- Set REM to DIVIDEND mod DIVISOR.
  2. Copyright 1991, 1993, 1994, 2000, 2001, 2005 Free Software Foundation, Inc.
  3. This file is part of the GNU MP Library.
  4. The GNU MP Library is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or (at your
  7. option) any later version.
  8. The GNU MP Library is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  10. or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
  11. License for more details.
  12. You should have received a copy of the GNU Lesser General Public License
  13. along with the GNU MP Library.  If not, see http://www.gnu.org/licenses/.  */
  14. #include "gmp.h"
  15. #include "gmp-impl.h"
  16. #include "longlong.h"
  17. void
  18. mpz_tdiv_r (mpz_ptr rem, mpz_srcptr num, mpz_srcptr den)
  19. {
  20.   mp_size_t ql;
  21.   mp_size_t ns, ds, nl, dl;
  22.   mp_ptr np, dp, qp, rp;
  23.   TMP_DECL;
  24.   ns = SIZ (num);
  25.   ds = SIZ (den);
  26.   nl = ABS (ns);
  27.   dl = ABS (ds);
  28.   ql = nl - dl + 1;
  29.   if (dl == 0)
  30.     DIVIDE_BY_ZERO;
  31.   MPZ_REALLOC (rem, dl);
  32.   if (ql <= 0)
  33.     {
  34.       if (num != rem)
  35. {
  36.   mp_ptr np, rp;
  37.   np = PTR (num);
  38.   rp = PTR (rem);
  39.   MPN_COPY (rp, np, nl);
  40.   SIZ (rem) = SIZ (num);
  41. }
  42.       return;
  43.     }
  44.   TMP_MARK;
  45.   qp = TMP_ALLOC_LIMBS (ql);
  46.   rp = PTR (rem);
  47.   np = PTR (num);
  48.   dp = PTR (den);
  49.   /* FIXME: We should think about how to handle the temporary allocation.
  50.      Perhaps mpn_tdiv_qr should handle it, since it anyway often needs to
  51.      allocate temp space.  */
  52.   /* Copy denominator to temporary space if it overlaps with the remainder.  */
  53.   if (dp == rp)
  54.     {
  55.       mp_ptr tp;
  56.       tp = TMP_ALLOC_LIMBS (dl);
  57.       MPN_COPY (tp, dp, dl);
  58.       dp = tp;
  59.     }
  60.   /* Copy numerator to temporary space if it overlaps with the remainder.  */
  61.   if (np == rp)
  62.     {
  63.       mp_ptr tp;
  64.       tp = TMP_ALLOC_LIMBS (nl);
  65.       MPN_COPY (tp, np, nl);
  66.       np = tp;
  67.     }
  68.   mpn_tdiv_qr (qp, rp, 0L, np, nl, dp, dl);
  69.   MPN_NORMALIZE (rp, dl);
  70.   SIZ (rem) = ns >= 0 ? dl : -dl;
  71.   TMP_FREE;
  72. }