1 /* mpn_pow_1 -- Compute powers R = U^exp. 2 3 THE FUNCTIONS IN THIS FILE ARE FOR INTERNAL USE ONLY. THEY'RE ALMOST 4 CERTAIN TO BE SUBJECT TO INCOMPATIBLE CHANGES OR DISAPPEAR COMPLETELY IN 5 FUTURE GNU MP RELEASES. 6 7 Copyright 2002 Free Software Foundation, Inc. 8 9 This file is part of the GNU MP Library. 10 11 The GNU MP Library is free software; you can redistribute it and/or modify it 12 under the terms of the GNU Lesser General Public License as published by the 13 Free Software Foundation; either version 3 of the License, or (at your 14 option) any later version. 15 16 The GNU MP Library is distributed in the hope that it will be useful, but 17 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 18 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License 19 for more details. 20 21 You should have received a copy of the GNU Lesser General Public License along 22 with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */ 23 24 25 #include "gmp.h" 26 #include "gmp-impl.h" 27 #include "longlong.h" 28 29 mp_size_t 30 mpn_pow_1 (mp_ptr rp, mp_srcptr bp, mp_size_t bn, mp_limb_t exp, mp_ptr tp) 31 { 32 mp_limb_t x; 33 int cnt, i; 34 mp_size_t rn; 35 int par; 36 37 if (exp <= 1) 38 { 39 if (exp == 0) 40 { 41 rp[0] = 1; 42 return 1; 43 } 44 else 45 { 46 MPN_COPY (rp, bp, bn); 47 return bn; 48 } 49 } 50 51 /* Count number of bits in exp, and compute where to put initial square in 52 order to magically get results in the entry rp. Use simple code, 53 optimized for small exp. For large exp, the bignum operations will take 54 so much time that the slowness of this code will be negligible. */ 55 par = 0; 56 cnt = GMP_LIMB_BITS; 57 for (x = exp; x != 0; x >>= 1) 58 { 59 par ^= x & 1; 60 cnt--; 61 } 62 exp <<= cnt; 63 64 if (bn == 1) 65 { 66 mp_limb_t bl = bp[0]; 67 68 if ((cnt & 1) != 0) 69 MP_PTR_SWAP (rp, tp); 70 71 mpn_sqr_n (rp, bp, bn); 72 rn = 2 * bn; rn -= rp[rn - 1] == 0; 73 74 for (i = GMP_LIMB_BITS - cnt - 1;;) 75 { 76 exp <<= 1; 77 if ((exp & GMP_LIMB_HIGHBIT) != 0) 78 { 79 rp[rn] = mpn_mul_1 (rp, rp, rn, bl); 80 rn += rp[rn] != 0; 81 } 82 83 if (--i == 0) 84 break; 85 86 mpn_sqr_n (tp, rp, rn); 87 rn = 2 * rn; rn -= tp[rn - 1] == 0; 88 MP_PTR_SWAP (rp, tp); 89 } 90 } 91 else 92 { 93 if (((par ^ cnt) & 1) == 0) 94 MP_PTR_SWAP (rp, tp); 95 96 mpn_sqr_n (rp, bp, bn); 97 rn = 2 * bn; rn -= rp[rn - 1] == 0; 98 99 for (i = GMP_LIMB_BITS - cnt - 1;;) 100 { 101 exp <<= 1; 102 if ((exp & GMP_LIMB_HIGHBIT) != 0) 103 { 104 rn = rn + bn - (mpn_mul (tp, rp, rn, bp, bn) == 0); 105 MP_PTR_SWAP (rp, tp); 106 } 107 108 if (--i == 0) 109 break; 110 111 mpn_sqr_n (tp, rp, rn); 112 rn = 2 * rn; rn -= tp[rn - 1] == 0; 113 MP_PTR_SWAP (rp, tp); 114 } 115 } 116 117 return rn; 118 } 119