algorithm.hpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. Copyright (c) Marshall Clow 2014.
  3. Distributed under the Boost Software License, Version 1.0. (See accompanying
  4. file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. Revision history:
  6. 2 Dec 2014 mtc First version; power
  7. */
  8. /// \file algorithm.hpp
  9. /// \brief Misc Algorithms
  10. /// \author Marshall Clow
  11. ///
  12. #ifndef BOOST_ALGORITHM_HPP
  13. #define BOOST_ALGORITHM_HPP
  14. #include <boost/utility/enable_if.hpp> // for boost::disable_if
  15. #include <boost/type_traits/is_integral.hpp>
  16. namespace boost { namespace algorithm {
  17. template <typename T>
  18. T identity_operation ( std::multiplies<T> ) { return T(1); }
  19. template <typename T>
  20. T identity_operation ( std::plus<T> ) { return T(0); }
  21. /// \fn power ( T x, Integer n )
  22. /// \return the value "x" raised to the power "n"
  23. ///
  24. /// \param x The value to be exponentiated
  25. /// \param n The exponent (must be >= 0)
  26. ///
  27. // \remark Taken from Knuth, The Art of Computer Programming, Volume 2:
  28. // Seminumerical Algorithms, Section 4.6.3
  29. template <typename T, typename Integer>
  30. typename boost::enable_if<boost::is_integral<Integer>, T>::type
  31. power (T x, Integer n) {
  32. T y = 1; // Should be "T y{1};"
  33. if (n == 0) return y;
  34. while (true) {
  35. if (n % 2 == 1) {
  36. y = x * y;
  37. if (n == 1)
  38. return y;
  39. }
  40. n = n / 2;
  41. x = x * x;
  42. }
  43. return y;
  44. }
  45. /// \fn power ( T x, Integer n, Operation op )
  46. /// \return the value "x" raised to the power "n"
  47. /// using the operaton "op".
  48. ///
  49. /// \param x The value to be exponentiated
  50. /// \param n The exponent (must be >= 0)
  51. /// \param op The operation used
  52. ///
  53. // \remark Taken from Knuth, The Art of Computer Programming, Volume 2:
  54. // Seminumerical Algorithms, Section 4.6.3
  55. template <typename T, typename Integer, typename Operation>
  56. typename boost::enable_if<boost::is_integral<Integer>, T>::type
  57. power (T x, Integer n, Operation op) {
  58. T y = identity_operation(op);
  59. if (n == 0) return y;
  60. while (true) {
  61. if (n % 2 == 1) {
  62. y = op(x, y);
  63. if (n == 1)
  64. return y;
  65. }
  66. n = n / 2;
  67. x = op(x, x);
  68. }
  69. return y;
  70. }
  71. }}
  72. #endif // BOOST_ALGORITHM_HPP