new beta-0.90.0
[luatex.git] / source / libs / gmp / gmp-src / mpf / pow_ui.c
blob6d0528bedb20162425b208bab369670c4ca9d99f
1 /* mpf_pow_ui -- Compute b^e.
3 Copyright 1998, 1999, 2001, 2012, 2015 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 either:
10 * the GNU Lesser General Public License as published by the Free
11 Software Foundation; either version 3 of the License, or (at your
12 option) any later version.
16 * the GNU General Public License as published by the Free Software
17 Foundation; either version 2 of the License, or (at your option) any
18 later version.
20 or both in parallel, as here.
22 The GNU MP Library is distributed in the hope that it will be useful, but
23 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
24 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
25 for more details.
27 You should have received copies of the GNU General Public License and the
28 GNU Lesser General Public License along with the GNU MP Library. If not,
29 see https://www.gnu.org/licenses/. */
31 #include "gmp.h"
32 #include "gmp-impl.h"
33 #include "longlong.h"
35 /* This uses a plain right-to-left square-and-multiply algorithm.
37 FIXME: When popcount(e) is not too small, it would probably speed things up
38 to use a k-ary sliding window algorithm. */
40 void
41 mpf_pow_ui (mpf_ptr r, mpf_srcptr b, unsigned long int e)
43 mpf_t t;
44 int cnt;
46 if (e <= 1)
48 if (e == 0)
49 mpf_set_ui (r, 1);
50 else
51 mpf_set (r, b);
52 return;
55 count_leading_zeros (cnt, (mp_limb_t) e);
56 cnt = GMP_LIMB_BITS - 1 - cnt;
58 /* Increase computation precision as a function of the exponent. Adding
59 log2(popcount(e) + log2(e)) bits should be sufficient, but we add log2(e),
60 i.e. much more. With mpf's rounding of precision to whole limbs, this
61 will be excessive only when limbs are artificially small. */
62 mpf_init2 (t, mpf_get_prec (r) + cnt);
64 mpf_set (t, b); /* consume most significant bit */
65 while (--cnt > 0)
67 mpf_mul (t, t, t);
68 if ((e >> cnt) & 1)
69 mpf_mul (t, t, b);
72 /* Do the last iteration specially in order to save a copy operation. */
73 if (e & 1)
75 mpf_mul (t, t, t);
76 mpf_mul (r, t, b);
78 else
80 mpf_mul (r, t, t);
83 mpf_clear (t);