Listing 2: The logarithmic power algorithm

template<typename T>
T Power(T base, int exp) {
  assert( 0 <= exp );
  
  T pow = T(1);
  T x = base;
  if( exp % 2 )
    pow *= x;
  while(1 < exp) {
    x *= x;
    exp /= 2;
    if( exp % 2 )
      pow *= x;
  }
  return pow;
}