[LintCode]Fast Power
Version 1 O(n) 超时
class Solution {
/*
* @param a, b, n: 32bit integers
* @return: An integer
*/
public int fastPower(int a, int b, int n) {
// 2015-09-16 O(n)
if (n == 0) {
return 1 % b;
}
long product = 1;
for (int i = 0; i < n; i++) {
product = (product * a) % b;
}
return (int)product;
}
};
Version 2
class Solution {
/*
* @param a, b, n: 32bit integers
* @return: An integer
*/
public int fastPower(int a, int b, int n) {
// 2015-09-16 递归 O(logn)
// 为了防止溢出,每次乘完都要%
if (n == 1) {
return a % b;
}
if (n == 0) {
return 1 % b;
}
long product = fastPower(a, b, n / 2);
product = (product * product) % b;
if (n % 2 == 1) {
product = (product * a) % b;
}
return (int) product;
}
};