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
/*
原理根据等式: ab % k = (a%k)(b%k)%k
由于幂在此处以vector存储,因此需要逐位处理
观察如下情况:
a^1234567 % k = (a^1234560 % k) * (a^7 % k) % k = (a^123456 % k)^10 % k * (a^7 % k) % k
令b = [1 2 3 4 5 6 7], 有a^b % k = (a^(b-b % 10) % k)*(a^(b % 10) % k) % k = (a^(b/10)%k)^10 % k *(a^(b % 10) % k) % k = ....,
以powmod(a,b)代表求幂操作,则有: powmod(a,b) = powmod(a,(b - b % 10))% k * powmod(a,b%10)% k % k = powmod(powmod(a,b/10)%k,10) % k * powmod(a,b%10)% k % k = ....
再以上基础,以f(a,b)代表求幂的基础上的求余操作: f(a,b) = f(a,(b - b % 10)) * f(a, b%10)%k = f(f(a,b/10),10)*f(a,b%10)%k
*/
using namespace std;
class Solution {
const int k = 1337;
public:
int powmod(int a, int b){
int result = 1;
for (int i = 0; i != b; ++i){
result *= a;
result = result % k;
}
return result;
}
int superPow(int a, vector<int>& b) {
if (b.empty()) return 1;
int last = b.back();//逐位处理
b.pop_back();
return powmod(superPow(a, b), 10)*powmod(a, last) % k;
}
};