Comparisons have been proposed that fix the problem, but in fact the problem is that there should not be a floating point at all. You want an exact answer to the question regarding integers, and not approximation of calculations performed on inherently inaccurate measurements.
So how else can this be done?
The first thing that comes to mind is a hoax:
double guess = Math.Pow(num, 1.0 / power); return num == exponentiateBySquaring((int)guess, power) || num == exponentiateBySquaring((int)Math.Ceil(guess), power);
It will work as long as the guess is less than 1. But I cannot guarantee that it will always work on your inputs, because this condition is not always fulfilled.
So hereβs what comes to mind: binary search (the option where you first look for the upper bound) for base in exponentiateBySquaring(base, power) , for which the result is close to num . If and only if the closest answer is num (and they are both integers, so this comparison is pure), then num is the power degree. If there is no overflow (should not be), this should always work.
harold
source share