Description:
计算an % b,其中a,b和n都是32位的整数。
Explanation:
例如 231 % 3 = 2
例如 1001000 % 1000 = 0
Solution:
每次对n/2,减少一半的计算量,直至n=0或n=1;每次返回余数,平方再求余。注意n是奇数偶数,如果是技术,要补回舍去的1次幂,即乘以a%b,再求余。
class Solution {
/*
* @param a, b, n: 32bit integers
* @return: An integer
*/
public int fastPower(int a, int b, int n) {
// write your code here
if(n == 0){
return 1%b;
}else if(n == 1){
return a%b;
}
long remainder = (long)fastPower(a , b , n/2);
remainder = remainder * remainder % b;
if(n%2 == 1){
remainder = remainder * (a%b) % b;
}
return (int)remainder;
}
};