pow_i8_i8.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* Support routines for the intrinsic power (**) operator.
  2. Copyright (C) 2004-2015 Free Software Foundation, Inc.
  3. Contributed by Paul Brook
  4. This file is part of the GNU Fortran 95 runtime library (libgfortran).
  5. Libgfortran is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU General Public
  7. License as published by the Free Software Foundation; either
  8. version 3 of the License, or (at your option) any later version.
  9. Libgfortran is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. Under Section 7 of GPL version 3, you are granted additional
  14. permissions described in the GCC Runtime Library Exception, version
  15. 3.1, as published by the Free Software Foundation.
  16. You should have received a copy of the GNU General Public License and
  17. a copy of the GCC Runtime Library Exception along with this program;
  18. see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
  19. <http://www.gnu.org/licenses/>. */
  20. #include "libgfortran.h"
  21. /* Use Binary Method to calculate the powi. This is not an optimal but
  22. a simple and reasonable arithmetic. See section 4.6.3, "Evaluation of
  23. Powers" of Donald E. Knuth, "Seminumerical Algorithms", Vol. 2, "The Art
  24. of Computer Programming", 3rd Edition, 1998. */
  25. #if defined (HAVE_GFC_INTEGER_8) && defined (HAVE_GFC_INTEGER_8)
  26. GFC_INTEGER_8 pow_i8_i8 (GFC_INTEGER_8 a, GFC_INTEGER_8 b);
  27. export_proto(pow_i8_i8);
  28. GFC_INTEGER_8
  29. pow_i8_i8 (GFC_INTEGER_8 a, GFC_INTEGER_8 b)
  30. {
  31. GFC_INTEGER_8 pow, x;
  32. GFC_INTEGER_8 n;
  33. GFC_UINTEGER_8 u;
  34. n = b;
  35. x = a;
  36. pow = 1;
  37. if (n != 0)
  38. {
  39. if (n < 0)
  40. {
  41. if (x == 1)
  42. return 1;
  43. if (x == -1)
  44. return (n & 1) ? -1 : 1;
  45. return (x == 0) ? 1 / x : 0;
  46. }
  47. else
  48. {
  49. u = n;
  50. }
  51. for (;;)
  52. {
  53. if (u & 1)
  54. pow *= x;
  55. u >>= 1;
  56. if (u)
  57. x *= x;
  58. else
  59. break;
  60. }
  61. }
  62. return pow;
  63. }
  64. #endif