algorithm.hpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 <functional> // for plus and multiplies
  15. #include <boost/utility/enable_if.hpp> // for boost::disable_if
  16. #include <boost/type_traits/is_integral.hpp>
  17. namespace boost { namespace algorithm {
  18. template <typename T>
  19. BOOST_CXX14_CONSTEXPR T identity_operation ( std::multiplies<T> ) { return T(1); }
  20. template <typename T>
  21. BOOST_CXX14_CONSTEXPR T identity_operation ( std::plus<T> ) { return T(0); }
  22. /// \fn power ( T x, Integer n )
  23. /// \return the value "x" raised to the power "n"
  24. ///
  25. /// \param x The value to be exponentiated
  26. /// \param n The exponent (must be >= 0)
  27. ///
  28. // \remark Taken from Knuth, The Art of Computer Programming, Volume 2:
  29. // Seminumerical Algorithms, Section 4.6.3
  30. template <typename T, typename Integer>
  31. BOOST_CXX14_CONSTEXPR typename boost::enable_if<boost::is_integral<Integer>, T>::type
  32. power (T x, Integer n) {
  33. T y = 1; // Should be "T y{1};"
  34. if (n == 0) return y;
  35. while (true) {
  36. if (n % 2 == 1) {
  37. y = x * y;
  38. if (n == 1)
  39. return y;
  40. }
  41. n = n / 2;
  42. x = x * x;
  43. }
  44. return y;
  45. }
  46. /// \fn power ( T x, Integer n, Operation op )
  47. /// \return the value "x" raised to the power "n"
  48. /// using the operation "op".
  49. ///
  50. /// \param x The value to be exponentiated
  51. /// \param n The exponent (must be >= 0)
  52. /// \param op The operation used
  53. ///
  54. // \remark Taken from Knuth, The Art of Computer Programming, Volume 2:
  55. // Seminumerical Algorithms, Section 4.6.3
  56. template <typename T, typename Integer, typename Operation>
  57. BOOST_CXX14_CONSTEXPR typename boost::enable_if<boost::is_integral<Integer>, T>::type
  58. power (T x, Integer n, Operation op) {
  59. T y = identity_operation(op);
  60. if (n == 0) return y;
  61. while (true) {
  62. if (n % 2 == 1) {
  63. y = op(x, y);
  64. if (n == 1)
  65. return y;
  66. }
  67. n = n / 2;
  68. x = op(x, x);
  69. }
  70. return y;
  71. }
  72. }}
  73. #endif // BOOST_ALGORITHM_HPP