1 /* mpz_pow_ui(res, base, exp) -- Set RES to BASE**EXP.
3 Copyright (C) 1991 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 General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 The GNU MP Library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with the GNU MP Library; see the file COPYING. If not, write to
19 the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
28 mpz_pow_ui (MP_INT *r, const MP_INT *b, unsigned long int e)
35 #else /* BERKELEY_MP */
38 rpow (const MP_INT *b, signed short int e, MP_INT *r)
45 #endif /* BERKELEY_MP */
47 mp_ptr rp, bp, tp, xp;
51 bsize = ABS (b->size);
53 /* Single out cases that give result == 0 or 1. These tests are here
54 to simplify the general code below, not to optimize. */
71 /* Count the number of leading zero bits of the base's most
73 count_leading_zeros (cnt, b->d[bsize - 1]);
75 /* Over-estimate space requirements and allocate enough space for the
76 final result in two temporary areas. The two areas are used to
77 alternately hold the input and recieve the product for mpn_mul.
78 (This scheme is used to fulfill the requirements of mpn_mul; that
79 the product space may not be the same as any of the input operands.) */
80 rsize = bsize * e - cnt * e / BITS_PER_MP_LIMB;
82 rp = (mp_ptr) alloca (rsize * BYTES_PER_MP_LIMB);
83 tp = (mp_ptr) alloca (rsize * BYTES_PER_MP_LIMB);
86 MPN_COPY (rp, bp, bsize);
88 count_leading_zeros (cnt, e);
90 for (i = BITS_PER_MP_LIMB - cnt - 2; i >= 0; i--)
92 rsize = mpn_mul (tp, rp, rsize, rp, rsize);
93 xp = tp; tp = rp; rp = xp;
95 if ((e & ((mp_limb) 1 << i)) != 0)
97 rsize = mpn_mul (tp, rp, rsize, bp, bsize);
98 xp = tp; tp = rp; rp = xp;
102 /* Now then we know the exact space requirements, reallocate if
104 if (r->alloc < rsize)
105 _mpz_realloc (r, rsize);
107 MPN_COPY (r->d, rp, rsize);
108 r->size = (e & 1) == 0 || b->size >= 0 ? rsize : -rsize;