1 /* mpfr_ui_pow_ui -- compute the power beetween two machine integer
3 Copyright 1999-2015 Free Software Foundation, Inc.
4 Contributed by the AriC and Caramel projects, INRIA.
6 This file is part of the GNU MPFR Library.
8 The GNU MPFR Library is free software; you can redistribute it and/or modify
9 it under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or (at your
11 option) any later version.
13 The GNU MPFR Library is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
16 License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with the GNU MPFR Library; see the file COPYING.LESSER. If not, see
20 http://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc.,
21 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */
23 #include "mpfr-impl.h"
26 mpfr_ui_pow_ui (mpfr_ptr x
, unsigned long int y
, unsigned long int n
,
36 MPFR_SAVE_EXPO_DECL (expo
);
38 if (MPFR_UNLIKELY (n
<= 1))
41 return mpfr_set_ui (x
, y
, rnd
); /* y^1 = y */
43 return mpfr_set_ui (x
, 1, rnd
); /* y^0 = 1 for any y */
45 else if (MPFR_UNLIKELY (y
<= 1))
48 return mpfr_set_ui (x
, 1, rnd
); /* 1^n = 1 for any n > 0 */
50 return mpfr_set_ui (x
, 0, rnd
); /* 0^n = 0 for any n > 0 */
53 for (size_n
= 0, m
= n
; m
; size_n
++, m
>>= 1);
55 MPFR_SAVE_EXPO_MARK (expo
);
56 prec
= MPFR_PREC (x
) + 3 + size_n
;
57 mpfr_init2 (res
, prec
);
59 MPFR_ZIV_INIT (loop
, prec
);
64 inexact
= mpfr_set_ui (res
, y
, MPFR_RNDU
);
66 /* now 2^(i-1) <= n < 2^i: i=1+floor(log2(n)) */
67 for (i
-= 2; i
>= 0; i
--)
69 inexact
|= mpfr_mul (res
, res
, res
, MPFR_RNDU
);
72 inexact
|= mpfr_mul_ui (res
, res
, y
, MPFR_RNDU
);
74 /* since the loop is executed floor(log2(n)) times,
75 we have err = 1+floor(log2(n)).
76 Since prec >= MPFR_PREC(x) + 4 + floor(log2(n)), prec > err */
79 if (MPFR_LIKELY (inexact
== 0
80 || MPFR_CAN_ROUND (res
, err
, MPFR_PREC (x
), rnd
)))
83 /* Actualisation of the precision */
84 MPFR_ZIV_NEXT (loop
, prec
);
85 mpfr_set_prec (res
, prec
);
89 inexact
= mpfr_set (x
, res
, rnd
);
93 MPFR_SAVE_EXPO_FREE (expo
);
94 return mpfr_check_range (x
, inexact
, rnd
);