在 O(log) 时间内计算 Java 中没有幂函数的幂

Calculating a power in Java without power function in O(log) time

一位潜在雇主向我提出了这个问题,我的回答显然不符合标准。有人可以帮忙吗?

Implement a function that calculates power(A,B), where A and B are positive integers, assuming there is no power function in your programming language. Also, assume A and B are of Big Integer type so that there is no arithmetic overflow. What is the computational complexity of your function? Can you come up with a solution that runs with log(B) time?

我只是给你一个提示。假设B为45,则A45 = A32 * A8 * A4 * A1。您可以计算 A1、A2、A4、A8, 等等,从 A 开始并在每次迭代中对其进行平方。