| 1 |
/* Support routines for the intrinsic power (**) operator |
| 2 |
for UNSIGNED, using modulo arithmetic. |
| 3 |
Copyright (C) 2025 Free Software Foundation, Inc. |
| 4 |
Contributed by Thomas Koenig. |
| 5 |
|
| 6 |
This file is part of the GNU Fortran 95 runtime library (libgfortran). |
| 7 |
|
| 8 |
Libgfortran is free software; you can redistribute it and/or |
| 9 |
modify it under the terms of the GNU General Public |
| 10 |
License as published by the Free Software Foundation; either |
| 11 |
version 3 of the License, or (at your option) any later version. |
| 12 |
|
| 13 |
Libgfortran is distributed in the hope that it will be useful, |
| 14 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 16 |
GNU General Public License for more details. |
| 17 |
|
| 18 |
Under Section 7 of GPL version 3, you are granted additional |
| 19 |
permissions described in the GCC Runtime Library Exception, version |
| 20 |
3.1, as published by the Free Software Foundation. |
| 21 |
|
| 22 |
You should have received a copy of the GNU General Public License and |
| 23 |
a copy of the GCC Runtime Library Exception along with this program; |
| 24 |
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see |
| 25 |
<http://www.gnu.org/licenses/>. */ |
| 26 |
|
| 27 |
#include "libgfortran.h" |
| 28 |
|
| 29 |
|
| 30 |
/* Use Binary Method to calculate the powi. This is not an optimal but |
| 31 |
a simple and reasonable arithmetic. See section 4.6.3, "Evaluation of |
| 32 |
Powers" of Donald E. Knuth, "Seminumerical Algorithms", Vol. 2, "The Art |
| 33 |
of Computer Programming", 3rd Edition, 1998. */ |
| 34 |
|
| 35 |
#if defined (HAVE_GFC_UINTEGER_16) && defined (HAVE_GFC_UINTEGER_4) |
| 36 |
|
| 37 |
GFC_UINTEGER_16 pow_m16_m4 (GFC_UINTEGER_16 x, GFC_UINTEGER_4 n); |
| 38 |
export_proto(pow_m16_m4); |
| 39 |
|
| 40 |
inline static GFC_UINTEGER_16 |
| 41 |
power_simple_m16_m4 (GFC_UINTEGER_16 x, GFC_UINTEGER_4 n) |
| 42 |
{ |
| 43 |
GFC_UINTEGER_16 pow = 1; |
| 44 |
for (;;) |
| 45 |
{ |
| 46 |
if (n & 1) |
| 47 |
pow *= x; |
| 48 |
n >>= 1; |
| 49 |
if (n) |
| 50 |
x *= x; |
| 51 |
else |
| 52 |
break; |
| 53 |
} |
| 54 |
return pow; |
| 55 |
} |
| 56 |
|
| 57 |
/* For odd x, Euler's theorem tells us that x**(2^(m-1)) = 1 mod 2^m. |
| 58 |
For even x, we use the fact that (2*x)^m = 0 mod 2^m. */ |
| 59 |
|
| 60 |
GFC_UINTEGER_16 |
| 61 |
pow_m16_m4 (GFC_UINTEGER_16 x, GFC_UINTEGER_4 n) |
| 62 |
{ |
| 63 |
const GFC_UINTEGER_16 mask = (GFC_UINTEGER_16) (-1) / 2; |
| 64 |
if (n == 0) |
| 65 |
return 1; |
| 66 |
|
| 67 |
if (x == 0) |
| 68 |
return 0; |
| 69 |
|
| 70 |
if (x & 1) |
| 71 |
return power_simple_m16_m4 (x, n & mask); |
| 72 |
|
| 73 |
if (n > sizeof (x) * 8) |
| 74 |
return 0; |
| 75 |
|
| 76 |
return power_simple_m16_m4 (x, n); |
| 77 |
} |
| 78 |
|
| 79 |
#endif |