The problem states that p ≤ 10^100
. There is no exact double
representation for all integers of that magnitude(*). If the closest floating point representation of p
is less than the exact p
, then the floating point value returned by pow(p, 1 / n);
will also be less than the expected k
.
When you convert a floating point number, the fractional part is truncated i.e. the number is rounded down. Therefore, if the calcucated floating point value k'
is less than the exact k
, then k'
converted to an integer will be k - 1
.
Since you're guaranteed to get a floating point number that is close to the correct integer by a small margin of error, you can solve the problem by rounding to the nearest integer, rather than rounding down. JSF already gave the algorithm for that: Add 0.5
before rounding down.
(*) 64-bit IEEE 754 floating point can represent integers exactly up to 10^17.
Also, there is a potential problem of the size of the result. If the size int
on the platform is 2 bytes, then k
will overflow. A 4 byte int
is sufficient for the given range of k
. You can guarantee the necessary size by using int32_t
.