Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.
Example1:
a = 2 b = [3] Result: 8
Example2:
a = 2 b = [1,0] Result: 1024
Credits:
Special thanks to @Stomach_ache for adding this problem and creating all test cases.
这里b是以数组的形式提供,意味着可能很长。这里采用递归的形式,递归条件是:
return (powMod(sPow(a, b, length - 1, k), 10, k) * powMod(a, b[length - 1], k)) % k;
代码如下:
public class Solution {
public int superPow(int a, int[] b) {
return sPow(a, b, b.length, 1337);
}
private int sPow(int a, int[] b, int length, int k) {
if (length == 1) {
return powMod(a, b[0], k);
}
return (powMod(sPow(a, b, length - 1, k), 10, k) * powMod(a, b[length - 1], k)) % k;
}
private int powMod(int a, int n, int k) {
a = a % k;
int result = 1;
for (int i = 0; i < n; i ++) {
result = (result * a) % k; //这里每算一步都%k对最后结果没有影响,还能防止a*a....*a*a溢出,比如9^10就会溢出。
}
return result;
}
}