A better recursive approach than Zed’s.
int myPow(int x, unsigned int p)
{
if (p == 0) return 1;
if (p == 1) return x;
int tmp = myPow(x, p/2);
if (p%2 == 0) return tmp * tmp;
else return x * tmp * tmp;
}
Much better complexity there O(log²(p)) instead of O(p).
Or as a constexpr
function using c++17.
template <unsigned int p>
int constexpr IntPower(const int x)
{
if constexpr (p == 0) return 1;
if constexpr (p == 1) return x;
int tmp = IntPower<p / 2>(x);
if constexpr ((p % 2) == 0) { return tmp * tmp; }
else { return x * tmp * tmp; }
}