Austin Schuh | bb1338c | 2024-06-15 19:31:16 -0700 | [diff] [blame] | 1 | /* mpf_pow_ui -- Compute b^e. |
| 2 | |
| 3 | Copyright 1998, 1999, 2001, 2012, 2015 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 either: |
| 9 | |
| 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. |
| 13 | |
| 14 | or |
| 15 | |
| 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. |
| 19 | |
| 20 | or both in parallel, as here. |
| 21 | |
| 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. |
| 26 | |
| 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/. */ |
| 30 | |
| 31 | #include "gmp-impl.h" |
| 32 | #include "longlong.h" |
| 33 | |
| 34 | /* This uses a plain right-to-left square-and-multiply algorithm. |
| 35 | |
| 36 | FIXME: When popcount(e) is not too small, it would probably speed things up |
| 37 | to use a k-ary sliding window algorithm. */ |
| 38 | |
| 39 | void |
| 40 | mpf_pow_ui (mpf_ptr r, mpf_srcptr b, unsigned long int e) |
| 41 | { |
| 42 | mpf_t t; |
| 43 | int cnt; |
| 44 | |
| 45 | if (e <= 1) |
| 46 | { |
| 47 | if (e == 0) |
| 48 | mpf_set_ui (r, 1); |
| 49 | else |
| 50 | mpf_set (r, b); |
| 51 | return; |
| 52 | } |
| 53 | |
| 54 | count_leading_zeros (cnt, (mp_limb_t) e); |
| 55 | cnt = GMP_LIMB_BITS - 1 - cnt; |
| 56 | |
| 57 | /* Increase computation precision as a function of the exponent. Adding |
| 58 | log2(popcount(e) + log2(e)) bits should be sufficient, but we add log2(e), |
| 59 | i.e. much more. With mpf's rounding of precision to whole limbs, this |
| 60 | will be excessive only when limbs are artificially small. */ |
| 61 | mpf_init2 (t, mpf_get_prec (r) + cnt); |
| 62 | |
| 63 | mpf_set (t, b); /* consume most significant bit */ |
| 64 | while (--cnt > 0) |
| 65 | { |
| 66 | mpf_mul (t, t, t); |
| 67 | if ((e >> cnt) & 1) |
| 68 | mpf_mul (t, t, b); |
| 69 | } |
| 70 | |
| 71 | /* Do the last iteration specially in order to save a copy operation. */ |
| 72 | if (e & 1) |
| 73 | { |
| 74 | mpf_mul (t, t, t); |
| 75 | mpf_mul (r, t, b); |
| 76 | } |
| 77 | else |
| 78 | { |
| 79 | mpf_mul (r, t, t); |
| 80 | } |
| 81 | |
| 82 | mpf_clear (t); |
| 83 | } |