The problem is that double
(and floating-point numbers in general) aren't exact and the math functions in the standard library also use approximate formulae to do the calculations. If you call pow(2, 10)
, you may get 1023.999375
, for example (which is then, depending on the context, may be truncated down to 1023
).
So, instead of using the floating-point pow()
function from the standard library, you can go with your own, exact implementation for integers:
int constexpr _pow(int base, int exp)
{
return exp == 0 ? 1 : base * _pow(base, exp - 1);
}
(or change it to whatever integral type you want if you need unsigned
or long long
).