题目链接:https://leetcode.com/problems/super-pow/#/description
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
用公式表示就是:假设f(a, b) 计算 a^b
% k,那么f(a,1234567) = f(a, 1234560) * f(a, 7) % k = f(f(a, 123456),10) * f(a,7)%k;
class Solution{
private:
const int base=1337;
//ex. (7^3)%k=(7*7*7)%k=((7%k)*((7*7)%k))%k=((7%k)*((7%k)*(7%k)%k))%k
int powmod(int a,int k)
{
a%=base;
int result=1;
for(int i=0;i<k;i++)
result=(result * a)%base;
return result;
}
public:
// ex. a^1234567 % k = (a^1234560 % k) * (a^7 % k) % k = (a^123456 % k)^10 % k * (a^7 % k) % k
int superPow(int a,vector<int>& b)
{
if(b.empty())
return 1;
int last_digit=b.back();
b.pop_back();
return powmod(superPow(a,b),10)*powmod(a,last_digit)%base;
}
};