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

Algorithm

Development Platform:

Unix_Linux

  1. /* mpz_remove -- divide out a factor and return its multiplicity.
  2. Copyright 1998, 1999, 2000, 2001, 2002 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. mp_bitcnt_t
  17. mpz_remove (mpz_ptr dest, mpz_srcptr src, mpz_srcptr f)
  18. {
  19.   mpz_t fpow[GMP_LIMB_BITS]; /* Really MP_SIZE_T_BITS */
  20.   mpz_t x, rem;
  21.   mp_bitcnt_t pwr;
  22.   int p;
  23.   if (mpz_cmp_ui (f, 1) <= 0)
  24.     DIVIDE_BY_ZERO;
  25.   if (SIZ (src) == 0)
  26.     {
  27.       if (src != dest)
  28.         mpz_set (dest, src);
  29.       return 0;
  30.     }
  31.   if (mpz_cmp_ui (f, 2) == 0)
  32.     {
  33.       mp_bitcnt_t s0;
  34.       s0 = mpz_scan1 (src, 0);
  35.       mpz_div_2exp (dest, src, s0);
  36.       return s0;
  37.     }
  38.   /* We could perhaps compute mpz_scan1(src,0)/mpz_scan1(f,0).  It is an
  39.      upper bound of the result we're seeking.  We could also shift down the
  40.      operands so that they become odd, to make intermediate values smaller.  */
  41.   mpz_init (rem);
  42.   mpz_init (x);
  43.   pwr = 0;
  44.   mpz_init (fpow[0]);
  45.   mpz_set (fpow[0], f);
  46.   mpz_set (dest, src);
  47.   /* Divide by f, f^2, ..., f^(2^k) until we get a remainder for f^(2^k).  */
  48.   for (p = 0;; p++)
  49.     {
  50.       mpz_tdiv_qr (x, rem, dest, fpow[p]);
  51.       if (SIZ (rem) != 0)
  52. break;
  53.       mpz_init (fpow[p + 1]);
  54.       mpz_mul (fpow[p + 1], fpow[p], fpow[p]);
  55.       mpz_set (dest, x);
  56.     }
  57.   pwr = (1L << p) - 1;
  58.   mpz_clear (fpow[p]);
  59.   /* Divide by f^(2^(k-1)), f^(2^(k-2)), ..., f for all divisors that give a
  60.      zero remainder.  */
  61.   while (--p >= 0)
  62.     {
  63.       mpz_tdiv_qr (x, rem, dest, fpow[p]);
  64.       if (SIZ (rem) == 0)
  65. {
  66.   pwr += 1L << p;
  67.   mpz_set (dest, x);
  68. }
  69.       mpz_clear (fpow[p]);
  70.     }
  71.   mpz_clear (x);
  72.   mpz_clear (rem);
  73.   return pwr;
  74. }