已经提出了解决问题的比较,但实际上这里的问题是根本不应该涉及浮点。您想要一个涉及整数的问题的准确答案,而不是对固有的不准确测量进行的计算的近似值。
那么这还能怎么做呢?
首先想到的是作弊:
double guess = Math.Pow(num, 1.0 / power);
return num == exponentiateBySquaring((int)guess, power) ||
num == exponentiateBySquaring((int)Math.Ceil(guess), power);
// do NOT replace exponentiateBySquaring with Math.Pow
只要guess
小于 1 就可以工作。但我不能保证它总是适用于您的输入,因为并不总是满足这个条件。
So here's the next thing that comes to mind: a binary search (the variant where you search for the upper boundary first) for the base
in exponentiateBySquaring(base, power)
for which the result is closest to num
. If and only if the closest answer is equal to num
(and they are both integers, so this comparison is clean), then num
is a power
-th power. Unless there is overflow (there shouldn't be), that should always work.