Initial import of binutils 2.22 on the new vendor branch
[dragonfly.git] / contrib / gmp / mpz / remove.c
1 /* mpz_remove -- divide out a factor and return its multiplicity.
2
3 Copyright 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
4
5 This file is part of the GNU MP Library.
6
7 The GNU MP Library is free software; you can redistribute it and/or modify
8 it under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or (at your
10 option) any later version.
11
12 The GNU MP Library is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
15 License for more details.
16
17 You should have received a copy of the GNU Lesser General Public License
18 along with the GNU MP Library.  If not, see http://www.gnu.org/licenses/.  */
19
20 #include "gmp.h"
21 #include "gmp-impl.h"
22
23 mp_bitcnt_t
24 mpz_remove (mpz_ptr dest, mpz_srcptr src, mpz_srcptr f)
25 {
26   mpz_t fpow[GMP_LIMB_BITS];            /* Really MP_SIZE_T_BITS */
27   mpz_t x, rem;
28   mp_bitcnt_t pwr;
29   int p;
30
31   if (mpz_cmp_ui (f, 1) <= 0)
32     DIVIDE_BY_ZERO;
33
34   if (SIZ (src) == 0)
35     {
36       if (src != dest)
37         mpz_set (dest, src);
38       return 0;
39     }
40
41   if (mpz_cmp_ui (f, 2) == 0)
42     {
43       mp_bitcnt_t s0;
44       s0 = mpz_scan1 (src, 0);
45       mpz_div_2exp (dest, src, s0);
46       return s0;
47     }
48
49   /* We could perhaps compute mpz_scan1(src,0)/mpz_scan1(f,0).  It is an
50      upper bound of the result we're seeking.  We could also shift down the
51      operands so that they become odd, to make intermediate values smaller.  */
52
53   mpz_init (rem);
54   mpz_init (x);
55
56   pwr = 0;
57   mpz_init (fpow[0]);
58   mpz_set (fpow[0], f);
59   mpz_set (dest, src);
60
61   /* Divide by f, f^2, ..., f^(2^k) until we get a remainder for f^(2^k).  */
62   for (p = 0;; p++)
63     {
64       mpz_tdiv_qr (x, rem, dest, fpow[p]);
65       if (SIZ (rem) != 0)
66         break;
67       mpz_init (fpow[p + 1]);
68       mpz_mul (fpow[p + 1], fpow[p], fpow[p]);
69       mpz_set (dest, x);
70     }
71
72   pwr = (1L << p) - 1;
73
74   mpz_clear (fpow[p]);
75
76   /* Divide by f^(2^(k-1)), f^(2^(k-2)), ..., f for all divisors that give a
77      zero remainder.  */
78   while (--p >= 0)
79     {
80       mpz_tdiv_qr (x, rem, dest, fpow[p]);
81       if (SIZ (rem) == 0)
82         {
83           pwr += 1L << p;
84           mpz_set (dest, x);
85         }
86       mpz_clear (fpow[p]);
87     }
88
89   mpz_clear (x);
90   mpz_clear (rem);
91   return pwr;
92 }