PR fortran/17631
[official-gcc.git] / libgfortran / generated / pow_i4_i4.c
blob15a349c1e9cbe505b784bf63c5e10efc07b35182
1 /* Support routines for the intrinsic power (**) operator.
2 Copyright 2004 Free Software Foundation, Inc.
3 Contributed by Paul Brook
5 This file is part of the GNU Fortran 95 runtime library (libgfor).
7 Libgfor is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public
9 License as published by the Free Software Foundation; either
10 version 2.1 of the License, or (at your option) any later version.
12 Ligbfor is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public
18 License along with libgfor; see the file COPYING.LIB. If not,
19 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
22 #include "config.h"
23 #include "libgfortran.h"
25 /* Uuse Binary Method to calculate the powi. This is not an optimal but
26 a simple and reasonable arithmetic. See section 4.6.3, "Evaluation of
27 Powers" of Donald E. Knuth, "Seminumerical Algorithms", Vol. 2, "The Art
28 of Computer Programming", 3rd Edition, 1998. */
30 GFC_INTEGER_4
31 prefix(pow_i4_i4) (GFC_INTEGER_4 a, GFC_INTEGER_4 b)
33 GFC_INTEGER_4 pow, x;
34 GFC_INTEGER_4 n, u;
36 n = b;
37 x = a;
38 pow = 1;
39 if (n != 0)
41 if (n < 0)
43 if (x == 1)
44 return 1;
45 if (x == -1)
46 return (n & 1) ? -1 : 1;
47 return (x == 0) ? 1 / x : 0;
49 u = n;
50 for (;;)
52 if (u & 1)
53 pow *= x;
54 u >>= 1;
55 if (u)
56 x *= x;
57 else
58 break;
61 return pow;