1 /* mpz_pow_ui(res, base, exp) -- Set RES to BASE**EXP.
3 Copyright (C) 1991, 1993, 1994, 1996, 1997 Free Software Foundation, Inc.
5 This file is part of the GNU MP Library.
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 2.1 of the License, or (at your
10 option) any later version.
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.
17 You should have received a copy of the GNU Lesser General Public License
18 along with the GNU MP Library; see the file COPYING.LIB. If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20 MA 02111-1307, USA. */
32 mpz_pow_ui (mpz_ptr r, mpz_srcptr b, unsigned long int e)
39 #else /* BERKELEY_MP */
42 rpow (const MINT *b, signed short int e, MINT *r)
49 #endif /* BERKELEY_MP */
51 mp_ptr rp, bp, tp, xp;
52 mp_size_t ralloc, rsize, bsize;
57 bsize = ABS (b->_mp_size);
59 /* Single out cases that give result == 0 or 1. These tests are here
60 to simplify the general code below, not to optimize. */
79 blimb = bp[bsize - 1];
80 if (bsize == 1 && blimb < 0x100)
82 /* Estimate space requirements accurately. Using the code from the
83 `else' path would over-estimate space requirements wildly. */
84 float lb = __mp_bases[blimb].chars_per_bit_exactly;
85 ralloc = 3 + ((mp_size_t) (e / lb) / BITS_PER_MP_LIMB);
89 /* Over-estimate space requirements somewhat. */
90 count_leading_zeros (cnt, blimb);
91 ralloc = bsize * e - cnt * e / BITS_PER_MP_LIMB + 2;
96 /* The two areas are used to alternatingly hold the input and recieve the
97 product for mpn_mul. (This scheme is used to fulfill the requirements
98 of mpn_mul; that the product space may not be the same as any of the
100 rp = (mp_ptr) TMP_ALLOC (ralloc * BYTES_PER_MP_LIMB);
101 tp = (mp_ptr) TMP_ALLOC (ralloc * BYTES_PER_MP_LIMB);
103 MPN_COPY (rp, bp, bsize);
105 count_leading_zeros (cnt, e);
107 for (i = BITS_PER_MP_LIMB - cnt - 2; i >= 0; i--)
109 mpn_mul_n (tp, rp, rp, rsize);
111 rsize -= tp[rsize - 1] == 0;
112 xp = tp; tp = rp; rp = xp;
114 if ((e & ((mp_limb_t) 1 << i)) != 0)
116 rsize = rsize + bsize - (mpn_mul (tp, rp, rsize, bp, bsize) == 0);
117 xp = tp; tp = rp; rp = xp;
121 /* Now then we know the exact space requirements, reallocate if
123 if (r->_mp_alloc < rsize)
124 _mpz_realloc (r, rsize);
126 MPN_COPY (r->_mp_d, rp, rsize);
127 r->_mp_size = (e & 1) == 0 || b->_mp_size >= 0 ? rsize : -rsize;