计算an % b,其中a,b和n都是32位的整数。
您在真实的面试中是否遇到过这个题?
Yes
样例
您在真实的面试中是否遇到过这个题?
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) ;
}
}
};