LintCode Fast Power
Calculate the an % b where a, b and n are all 32bit integers.
Have you met this question in a real interview? Yes
Example
For 231 % 3 = 2
For 1001000 % 1000 = 0
Challenge
O(logn)
迭代版本:
class Solution {
public:
/*
* @param a, b, n: 32bit integers
* @return: An integer
*/
int fastPower(int a, int b, int n) {
// write your code here
int res = 1;
long part = a;
while (n) {
if (n & 0x1) {
res = res * part % b;
}
part = part * part % b;
n /= 2;
}
return res % b;
}
};