计算an % b,其中a,b和n都是32位的整数。
样例
例如 231 % 3 = 2
例如 1001000 % 1000 = 0
挑战
O(logn)
class Solution {
public:
int fastPower(int a, int b, int n) {
if(0==n)
return 1%b;
if(1==n)
return a%b;
long Pow=fastPower(a,b,n/2);
Pow=(Pow*Pow)%b;
if(n&1)
return (a*Pow)%b;
return Pow;
}
};
本文介绍了一个利用递归实现的快速幂运算算法,该算法的时间复杂度为O(logn),适用于32位整数的快速幂计算。

505

被折叠的 条评论
为什么被折叠?



