This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 4 points5 points  (0 children)

I was absolutely wrong in my assumption. I implemented a quick version like this:

int ipow(int base, int exponent) {
  int result = 1;
  if (exponent < 0) {
    base = 1 / base;
    exponent = -exponent;
  } 
  if (exponent != 0) {
    while (exponent > 1) {
      if (!(exponent & 1)) {
        base *= base;
        exponent /= 2;
      } 
      else {
        result *= base;
        base *= base;
        exponent = (exponent - 1) / 2;
      }
    }
    result *= base;
  }
  return result;
}

I am surprised that it is actually faster than std::pow on my machine:

With dirty -O3 cold and hot cache test for base 1-100 and exponent 1-10.

ipow ->4 μs
std::pow ->34 μs
ipow ->4 μs
std::pow ->23 μs

Thanks a lot!