Why isn't `int pow(int base, int exponent)` in the standard C++ libraries?

前端 未结 11 1380
礼貌的吻别
礼貌的吻别 2020-11-27 02:20

I feel like I must just be unable to find it. Is there any reason that the C++ pow function does not implement the \"power\" function for anything except

11条回答
  •  孤街浪徒
    2020-11-27 03:16

    Here's a really simple O(log(n)) implementation of pow() that works for any numeric types, including integers:

    template
    static constexpr inline T pown(T x, unsigned p) {
        T result = 1;
    
        while (p) {
            if (p & 0x1) {
                result *= x;
            }
            x *= x;
            p >>= 1;
        }
    
        return result;
    }
    

    It's better than enigmaticPhysicist's O(log(n)) implementation because it doesn't use recursion.

    It's also almost always faster than his linear implementation (as long as p > ~3) because:

    • it doesn't require any extra memory
    • it only does ~1.5x more operations per loop
    • it only does ~1.25x more memory updates per loop

提交回复
热议问题