您的位置:首页 > 其它

Fast Power

2016-07-23 04:57 274 查看
Calculate the a^n % b where a, b and n are all 32bit integers.

Example

For 2^31 % 3 = 2

For 100^1000 % 1000 = 0

分析:

利用公式:

(a * b) % p = (a % p * b % p) % p
a^n % b = (a^(n/2) * a^(n/2) * (a)) %b = ((a^(n/2) * a^(n/2))%b * (a)%b) %b = ((a^(n/2)%b * a^(n/2)%b)%b * (a)%b) %b

class Solution {
/*
* @param a, b, n: 32bit integers
* @return: An integer
*/
public int fastPower(int a, int b, int n) {

if (a == 0) return 0;
if (n == 0) return 1 % b;
if (n == 1 || a == 1) return a % b;

long temp =  fastPower(a, b, n / 2);
temp = temp * temp;
temp = temp % b;
if (n % 2 == 1) {
temp = temp * (a % b);
return (int)(temp % b);
} else {
return (int)temp;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: