您的位置:首页 > 其它

题目:快速幂

2015-09-29 00:02 92 查看


计算an % b,其中a,b和n都是32位的整数。

您在真实的面试中是否遇到过这个题?

Yes

样例

例如 2^31 % 3 = 2

例如 100^1000 % 1000 = 0

挑战

O(logn)

标签 Expand

相关题目 Expand

解题思路:
2分算法
class Solution {
/*
* @param a, b, n: 32bit integers
* @return: An integer
*/
int fastres  = 1;
public int fastPower(int a, int b, int n) {
// write your code here
if (n <= 0) {
return 1 % b;
}
if (n == 1) {
return  a % b;
} else {
long midtmp = fastPower(a, b, n/2);
if (n % 2 == 0)
return (int) ((midtmp%b*midtmp%b)%b) ;
else
return (int) ((a%b*midtmp%b*midtmp%b)%b) ;
}

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: